Java time tracking: using currentTimeMills ()

Today I got an interesting time issue 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 this is not repeatable. Does anyone know what happened inside while working? Just curious...

New edit: I used a little test to confirm 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 is closed. Thanks guys!

More words: currentTimeMillis () and nanoTime () are based on the system timer, so they will not be monotonous if the system timer is updated (in particular, vice versa). For such cases, it is better to use an Internet timer.

+6
source share
2 answers

System.currentTimeMillis() depends on the system time. Therefore, it can be modified by third-party systems.

For measuring time, System.nanoTime() best option.

+11
source

I recall something like time adjustments made for the system time, once too coinciding with the actual time. And since currentTimeMillis relies on a system clock that could happen. You also synchronize with a time server, which can also be.

0
source

Source: https://habr.com/ru/post/906580/


All Articles