java 如何计算Java中两个事件之间的时间差?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4532202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:47:36  来源:igfitidea点击:

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

javadatetime

提问by Space Rocker

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?

我想计算时间瞬间之间的时间差(以秒为单位)。例如,在程序执行期间,我设置了一个变量的值,一段时间后我再次更改它。最近的值变化与前一个值之间的时间差是多少?

回答by yurib

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.

您可以使用System.currentTimeMillis()以一毫秒的分辨率保存当前时间。只需在第一个事件发生时节省时间(最好使用 long var 来保存该值),并在第二个事件发生时再次节省时间。差值除以 1000 将为您提供以秒为单位的时间差。

回答by Roman

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 @Profiledannotation on methods and it will automatically generate some statistics and write it to a log file.

更成熟的方法(特别是,如果您需要在许多地方多次这样做)是使用库。看看perf4j。您可以@Profiled在方法上添加注释,它会自动生成一些统计信息并将其写入日志文件。

回答by Thorbj?rn Ravn Andersen

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.

存储从 检索到的当前时间System.nanoTime(),并减去这些值中的任意两个以获得以纳秒为单位的差异。

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

(通过整数除以一百万然后浮动一千,你会得到一个带三个小数位的秒数,这打印得很好。)

回答by zellio

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