Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the elapsed time of an event in java? [duplicate]

What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?

like image 489
kafuchau Avatar asked Oct 27 '08 02:10

kafuchau


People also ask

How is elapsed time calculated?

In simple words, we can say that the amount of time that has passed between the beginning and the end of an event is called the elapsed time. We can determine this time by subtracting the end time and the start time. The formula to calculate the elapsed time is simply to subtract the hours and minutes separately.


2 Answers

I would avoid using System.currentTimeMillis() for measuring elapsed time. currentTimeMillis() returns the 'wall-clock' time, which may change (eg: daylight savings, admin user changing the clock) and skew your interval measurements.

System.nanoTime(), on the other hand, returns the number of nanoseconds since 'some reference point' (eg, JVM start up), and would therefore not be susceptible to system clock changes.

like image 143
Leigh Avatar answered Oct 19 '22 11:10

Leigh


This is some sample code.

long startTime = System.currentTimeMillis(); // Run some code; long stopTime = System.currentTimeMillis();  System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds."); 
like image 44
jjnguy Avatar answered Oct 19 '22 11:10

jjnguy