How to calculate time difference between two events in Java?

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

+3
source share
4 answers

You can use System.currentTimeMillis()to save the current time with a resolution in milliseconds. Just save the time when the first event occurs (it is better to use a long var to store this value) and again when the second event occurs. The difference divided by 1000 will give you the time difference in seconds.

+8
source

You can do something simple:

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

long dt = end - begin;

A more mature way (especially if you need to do this many times in many places), use the library. Take a look at perf4j . You can put the annotation @Profiledon the methods, and it will automatically generate some statistics and write them to the log file.

+3
source

, , System.nanoTime(), , .

(Integer division, first in a million, and then floating in a thousand, you get time in seconds with three decimal places, which prints beautifully.)

+2
source

Just pick it up from the system and save it in long data. You can do the math at these lengths to figure out the time difference.

long start = System.currentTimeMillis();

//do stuff
//do more stuff

long end = System.currentTimeMillis();
+1
source

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


All Articles