2

I have searched the postings for an answer related to the time which the System.nanoTime( ) method call takes to process.

Consider the following code:

long lastTime = System.nanoTime();
long currentTime = System.nanoTime();
long deltaTime = currentTime - lastTime;

If you run this, currentTime - lastTime will evaluate to '0'. The only way for this to happen is if the computer processed that second method call outside of the resolution of a nanosecond (i.e. the call took less than a nanosecond). Logically this makes sense, because a computer can (on average) perform multiple processes in a single nanosecond.

Is this correct? If not, where is my logic wrong?

Jonathan
  • 589
  • 1
  • 13
  • 23
  • This is incorrect. Try running it. There is a time difference. On my android phone I get around 0.0015ms time difference. – JosephGarrone May 23 '13 at 00:49
  • A computer can perform a couple of *operations* in a single nanosecond, possibly per thread. Calling a Java function that interfaces with the system clock(s), though, typically takes quite a bit more than a couple of operations. – cHao May 23 '13 at 00:52
  • I did run it and I got a time difference of 0 nanoseconds. This is why I am confused. I would assume that the time delay would be larger than a nanosecond (like you said), but I'm not finding these results with the code above. – Jonathan May 23 '13 at 01:02
  • I found that if I run the code multiple times, I reach a case where the time difference is 383 nanoseconds. It doesn't consistently remain at that value however. What would cause this? – Jonathan May 23 '13 at 01:34

2 Answers2

0

well theoretically it will print out "0". In some cases it may have a slight variation if you have a lot of other tasks executing.

0

This is theoretically correct, assuming that there are absolutely no other processes running and that the call to the Java methods has no delay. So on a real system it is impossible to achieve as calls to the Java methods will introduce significant delays. As I stated in my comment, I can achieve around 0.015 millisecond difference on a dual core Android 4.0.4 phone.

JosephGarrone
  • 4,081
  • 3
  • 38
  • 61