java中的定时器精度 [英] Timer accuracy in java

查看:30
本文介绍了java中的定时器精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一些事情计时,我不能只是把它们放在一个长循环中.我需要给他们计时,看看他们需要多长时间才能完成,但似乎计时器在 Java 中的精度为 15-16 毫秒?我怎样才能解决这个问题?

I'm timing some things, which I can't just put in a long loop. And I need to time them to see how long they take to complete, but it seems like the timer has a 15-16 ms accuracy in java? How can i get around this?

推荐答案

您是否尝试过使用 System.nanoTime()?

来自 Javadoc:

From the Javadoc:

返回最精确的可用系统计时器的当前值,以纳秒为单位.

Returns the current value of the most precise available system timer, in nanoseconds.

此方法只能用于测量经过的时间,与系统或挂钟时间的任何其他概念无关.返回的值表示自某个固定但任意的时间以来的纳秒(可能在未来,因此值可能为负).此方法提供纳秒精度,但不一定提供纳秒精度.不保证值的更改频率.由于数值溢出,跨度超过大约 292 年(263 纳秒)的连续调用的差异将无法准确计算经过的时间.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

例如,衡量一些代码执行所需的时间:

For example, to measure how long some code takes to execute:

long startTime = System.nanoTime();//... 被测量的代码 ...长估计时间 = System.nanoTime() - startTime;

long startTime = System.nanoTime(); // ... the code being measured ... long estimatedTime = System.nanoTime() - startTime;

这篇关于java中的定时器精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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