Given the code below and it’s output, what could explain “1:” taking 80 times longer? If run in debug mode, the difference is reduced to 40x longer. Still a significant difference.
My first guess was JIT or other compiler optimizations. But that could be ruled out by adding multiple “timeNow()” and “println” calls (uncomment the commented section).
Also, I’ve added following flags in an attempt to turn them off:
-Djava.compiler=NONE
-XX:-TieredCompilation
Any explanation or guesses would be appreciated.
public class Test {
private static long lastTimestamp = -1;
/**
* Returns the elapsed time in microseconds since the last call to this method.
*
* @return Elapsed time in microseconds if this is not the first call, otherwise
* returns -1 to indicate the first call.
*/
public static long timeNow() {
long currentTime = System.nanoTime();
if (lastTimestamp == -1) {
// This is the first call
lastTimestamp = currentTime;
return -1; // Indicate that this is the first call
} else {
long elapsedTime = currentTime - lastTimestamp;
lastTimestamp = currentTime;
return elapsedTime / 1000; // Return elapsed time in microseconds
}
}
public static void main(String[] args) {
timeNow();
// timeNow();
// timeNow();
// timeNow();
//
// System.out.println("print");
// System.out.println("print");
// System.out.println("print");
System.out.println("0: " + timeNow());
System.out.println("1: " + timeNow());
System.out.println("2: " + timeNow());
System.out.println("3: " + timeNow());
}
}
Output: (repeated multiple time with similar results)
0: 2
1: 17897
2: 334
3: 217