开发者

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 chan开发者_如何学运维ge it again. What was the time difference between the recent change of value from the previous value?


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.


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.


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.)


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜