Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CPU execution time in Java

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.

like image 953
ravi Avatar asked Sep 19 '11 06:09

ravi


2 Answers

  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!
like image 200
Joachim Sauer Avatar answered Oct 01 '22 00:10

Joachim Sauer


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.

like image 31
Peter Lawrey Avatar answered Oct 01 '22 00:10

Peter Lawrey