CPU execution time in Java

倾然丶 夕夏残阳落幕 提交于 2019-11-26 16:31:34

问题


I want to calculate how much CPU time my function takes to execute in Java. Currently I am doing as below.

   long startTime = System.currentTimeMillis();
    myfunction();
    long endTime = System.currentTimeMillis();
    long searchTime = endTime - startTime;

But I found out that for the same I/P I get different time depending on system load.

So, how to get exact CPU time my function took to execute.


回答1:


As the JVM warms up the amount of time taken will vary. The second time you run this will always be faster than the first. (The first time it has to load classes and call static blocks) After you have run the method 10,000 times it will be faster again (The default threshold at which it compiles code to native machine code)

To get a reproducable average timing for a micro-benchmark, I suggest you ignore the first 10,000 iterations and run it for 2-10 seconds after that.

e.g.

long start = 0;
int runs = 10000; // enough to run for 2-10 seconds.
for(int i=-10000;i<runs;i++) {
    if(i == 0) start = System.nanoTime();
    // do test
}
long time = System.nanoTime() - start;
System.out.printf("Each XXXXX took an average of %,d ns%n", time/runs);

Very important: Only do one of these loops per method. This is because it optimises the whole method based on how it is used. If you have one busy loop like this the later loops will appear slower because they have not run and will be optimised poorly.




回答2:


  1. System.currentTimeMillis() will only ever measure wall-clock time, never CPU time.
  2. If you need wall-clock time, then System.nanoTime() is often more precise (and never worse) than currentTimeMillis().
  3. ThreadMXBean.getThreadCPUTime() can help you find out how much CPU time a given thread has used. Use ManagementFactory.getThreadMXBean() to get a ThreadMXBean and Thread.getId() to find the id of the thread you're interested in. Note that this method need not be supported on every JVM!



回答3:


There are a number of profilers (Jprofile, Jprobe, Yourkit) available to analyze such data. And not only this, but much more...(such as memory utilization, thread details, etc.)




回答4:


you could look for your answer here:

How do I time a method's execution in Java?

there are many examples to calculate method's execution time



来源:https://stackoverflow.com/questions/7467245/cpu-execution-time-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!