After reading about similar topics on Stack Overflow, I wrote the following code to get an idea about how consistent System.nanoTime()
is.
It simply calls System.nanoTime()
before and after a method call to an empty void function, recording the elapsed time in the process. As you can see in the results, however, the first call always take the longest. What is the reason for this?
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
double start = System.nanoTime();
foo();
double end = System.nanoTime();
double diff = end - start;
System.out.println("Diff: " + diff);
}
}
public static void foo() {
}
}
Results:
Diff: 2765.0
Diff: 509.0
Diff: 236.0
Diff: 238.0
Diff: 230.0
Diff: 539.0
Diff: 359.0
Diff: 356.0
Diff: 380.0
Diff: 353.0
Note that I did read this question: Why does first call to java.io.File.createTempFile(String,String,File) take 5 seconds on Citrix?
Also, this link is helpful for future reference, but doesn't necessarily answer my specific question: How do I write a correct micro-benchmark in Java?