CPU execution time in Java

  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!

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.