Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time tracking in Java: using currentTimeMills()

Tags:

java

time

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.

like image 578
asksw0rder Avatar asked Jan 22 '12 10:01

asksw0rder


People also ask

What is the use of currenttimemillis in Java?

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.

How to get the current time in milli-seconds in Java?

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.

What is the use of currenttimemillis () method of system class?

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?

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.


1 Answers

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.

like image 155
Robin Avatar answered Oct 16 '22 00:10

Robin