I’m trying to record the time it takes for a method to complete. I was originally timing the method as a whole, but the numbers seemed a bit off so I decided to time each individual pass through the for loop.
The strange thing is that, as the loop progresses, the enqueue operation seems to get quicker and quicker each time. Each call of q.enqueue() is enqueueing an incremented string (“String1”, “String2”,….etc) to a linked list queue.
If I make num=100, each pass takes about 4,000 nanoseconds. However if I increase num to 100,000 I can see that the first few hundred passes take around 4,000 again, but they gradually get quicker and quicker, with the final hundred or so being either 316 nanoseconds or 0 nanoseconds.
I know that using nanotime isn’t going to be 100% accurate, but it’s clearly getting quicker as the loop progresses.
What’s happening here?
public static void enqueueLoop(int num, Queue q){
for (int i=0;i<num;i++){
long start, enqueueTime;
start = System.nanoTime();
q.enqueue("String" + (i+1));
qTime = System.nanoTime() - start;
System.out.println("Enqueue Operation took: " + NumberFormat.getInstance().format(qTime) + " nanoseconds");
}
}
The JIT (Just In Time compiler) kicks in after seeing that the code is reused a lot, and compiles it into native code.