Space Rocker
Space Rocker

Reputation: 787

How to calculate the time difference between two events in Java?

I want to calculate time difference in seconds between to time instants. For example, during execution of the program, I set the value of a variable and after some time I change it again. What was the time difference between the recent change of value from the previous value?

Upvotes: 10

Views: 14296

Answers (4)

yurib
yurib

Reputation: 8147

You can use System.currentTimeMillis() to save the current time at one millisecond resolution. Just save the time whenever the first event occurs (better use a long var to hold that value) and again when the 2nd event occurs. The difference divided by 1000 will give you time difference in seconds.

Upvotes: 14

Store the current time when you need to as retrieved from System.nanoTime(), and subtract any two of these values to get the difference in nanoseconds.

(By integer division first by a million and then float by a thousand you get a time in seconds with three decimal places, which prints nicely.)

Upvotes: 3

Roman
Roman

Reputation: 66156

You can do something as simple as this:

long begin = System.currentTimeMillis();
doWork();
long end = System.currentTimeMillis();

long dt = end - begin;

More mature way (especially, if you need to do it many time in many places) is using a library. Look at perf4j. You can put @Profiled annotation on methods and it will automatically generate some statistics and write it to a log file.

Upvotes: 5

zellio
zellio

Reputation: 32484

Just fetch it from the system and store in long data. You can do math on those longs to figure out the time differential.

long start = System.currentTimeMillis();

//do stuff
//do more stuff

long end = System.currentTimeMillis();

Upvotes: 1

Related Questions