使用System.currentTimeMillis()测量时差 [英] Measuring time differences using System.currentTimeMillis()

查看:81
本文介绍了使用System.currentTimeMillis()测量时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Java程序,并且我想知道某些操作集之间的时间差.对于这个问题,细节并不重要,但是让我们采取以下情形.

I have a simple java program, and I want to know the time difference between some set of operations. For this question the details are not important, but let us take the following scenario.

long beginTime = System.currentTimeMillis();

//Some operations. Let us asssume some database operations etc. which are time consuming.

//

long endTime = System.currentTimeMillis();

long difference = endTime - beginTime;

在计算机上运行代码时,差异有多可靠?

When the code is run on a machine, how reliable will the difference be?

让我们说,处理器开始执行我的代码中的某些指令,然后将上下文提供给另一个进程,该进程执行一段时间,然后返回执行与该Java进程相关的指令.

Let us say, that the processor starts executing some instructions from my code, then gives context to another process, which executes for some time, and then comes back to execute instructions related to this java process.

因此,时差应取决于计算机的当前状态,即正在运行多少个进程等?因此,在分析过程中,某些操作需要运行,这种机制不可靠吗?

So, the time difference should depend on the current state of my machine, i.e. how many processes are running etc? So, in profiling time it takes for some operations to run, is this mechanism not reliable?

推荐答案

System.currentTimeMillis()的粒度取决于实现方式和操作系统,通常约为10毫秒.

The granularity of System.currentTimeMillis() depends on the implementation and on the Operating system and is usually around 10 ms.

相反,请使用 System.nanoTime()来返回最精确的可用系统计时器的当前值(以纳秒为单位).请注意,您只能使用它来计算经过的时间,不能将其值用作绝对时间.

Instead use the System.nanoTime() which returns the current value of the most precise available system timer, in nanoseconds. Note that you can only use this to calculate elapsed time, you cannot use its value as an absolute time.

示例:

long startTime = System.nanoTime();
// do something you want to measure
long elapsedTimeNs = System.nanoTime() - startTime;

这篇关于使用System.currentTimeMillis()测量时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆