I got an interesting "time-travel" problem today, using the following code:
for (int i = 0; i < 1; i++){
long start = System.currentTimeMillis();
// Some code here
System.out.print(i + "\t" + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
// Some code here
System.out.println("\t" + (System.currentTimeMillis() - start));
}
And I got the result
0 15 -606
And it seems that it is not repeatable. Anyone has any clues on what happened inside during the running time? Just curious...
New edit: I used a small test to confirmed the answers below. I run the program and change the system time during the run, and finally repeat the "time-travel":
0 -3563323 163
Case closed. Thanks guys!
More words: both currentTimeMillis() and nanoTime() are system-timer based, so they will be not monotonic if the system timer is updated (turned back, specifically). It is better to use some internet-based timer for such cases.
Java System currentTimeMillis () Method The currentTimeMillis () method of System class returns current time in format of millisecond. Millisecond will be returned as unit of time.
In this example, we will make a call to System.currentTimeMillis () and get the current time in milli-seconds. We can use System.currentTimeMillis () to calculate the time taken to run a block of code in milli-seconds.
The currentTimeMillis () method of System class returns current time in format of millisecond. Millisecond will be returned as unit of time. Returns difference, measured in milliseconds, between current time and midnight January 1, 1970 UTC (coordinated universal time).
How to measure time taken by a function in java ? We can measure the time taken by a function in Java with the help of java.lang.System.currentTimeMillis () method. This method returns the current time in millisecond. We can call this method at the beginning and at the end of function and by the difference we measure the time taken by the function.
System.currentTimeMillis()
depends on the system time. So it could be modified by third party systems.
For measuring time is System.nanoTime()
the better option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With