Java System.nanoTime() 经过时间的巨大差异
我在一个 android 小部件中,检查两次调用 System.nanoTime() 之间经过的时间,这个数字很大。你如何用这个来衡量经过的时间?它应该是几分之一秒,但实际上却更长。谢谢
I'm in an android widget and checking elapsed time between two calls of System.nanoTime() and the number is huge. How do you measure elapsed time with this? It should be a fraction of a second and instead it's much more. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
System.nanoTime()
返回一个时间值,其粒度为纳秒;即 10-9 秒,如 javadoc。对System.nanoTime()
的两次调用之间相隔几分之一秒的差异必然是一个很大的数字。如果您想要更大粒度的时间度量,请考虑
System.currentTimeMillis()
...或者只需将纳秒值除以适当的 10 次方即可适合您的应用程序。请注意,在 Android 平台上,有 3 个不同的系统时钟支持不同的时间“度量”;请参阅
SystemClock
。如果您正在为 Android 平台显式编程,则应该阅读 javadoc 并决定哪种措施最适合您正在做的事情。供您参考,“nano-”是国际单位制 (SI) 定义的标准前缀之一 - 请参阅 http://physicals.nist.gov/cuu/Units/prefixes.html。
如果你真的认为“他们”弄错了,并且“纳米”太小,你可以随时写信给 NIST。我相信有人会很感激...:-)
The
System.nanoTime()
returns a time value whose granularity is a nanosecond; i.e. 10-9 seconds, as described in the javadoc. The difference between two calls toSystem.nanoTime()
that are a substantial fraction of a second apart is bound to be a large number.If you want a time measure with a larger granularity, consider
System.currentTimeMillis()
... or just divide the nanosecond values by an appropriate power of 10 to suit your application.Note that on the Android platform there are 3 distinct system clocks that support different "measures" of time; see
SystemClock
. If you are programming explicitly for the Android platform, you should read the javadoc and decide which measure is most appropriate to what you are doing.For your information, "nano-" is one of the standard prefixes defines by the International System of Units (SI) - see http://physics.nist.gov/cuu/Units/prefixes.html.
If you really think that "they" got it wrong and that "nano-" is too small, you could always write a letter to the NIST. I'm sure someone would appreciate it ... :-)
一秒包含 1,000,000,000 纳秒,因此只要您的数字在该范围内,就是合理的。
One seconds contains 1,000,000,000 nanoseconds, so as long as your number is in that range, it's reasonable.
如果您想要小数形式,只需取您的
value
/ 10^9,其中value
是您的nanoTime()
秒差。你的输出将是:
If you want it in fractional form, just take your
value
/ 10^9 wherevalue
is your difference innanoTime()
s.Your output would be: