Java System.nanoTime() 在运行时间上的巨大差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5023647/
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
Java System.nanoTime() huge difference in elapsed time
提问by Androider
I'm in and 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 fraaction of a second and instead its much more. Thanks
我在和 android 小部件中并检查 System.nanoTime() 两次调用之间经过的时间,并且这个数字很大。你如何用这个来衡量经过的时间?它应该是几分之一秒,而不是更多。谢谢
回答by Stephen C
The System.nanoTime()
returns a time value whose granularity is a nanosecond; i.e. 10-9seconds, as described in the javadoc. The difference between two calls to System.nanoTime()
that are a substantial fraction of a second apart is bound to be a large number.
所述System.nanoTime()
返回一个时间值,其粒度是纳秒; 即 10 -9秒,如javadoc中所述。两次调用之间相差System.nanoTime()
很大一部分的调用之间的差异必然是一个很大的数字。
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.
如果您想要一个更大粒度的时间度量,请考虑System.currentTimeMillis()
……或者只是将纳秒值除以适当的 10 次幂以适合您的应用程序。
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.
请注意,在 Android 平台上,有 3 个不同的系统时钟支持不同的时间“度量”;见SystemClock
。如果您正在为 Android 平台明确编程,您应该阅读 javadoc 并决定哪种措施最适合您的工作。
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.
供您参考,“nano-”是国际单位制 (SI) 定义的标准前缀之一 - 请参阅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 ... :-)
如果您真的认为“他们”弄错了并且“nano-”太小,您可以随时给 NIST 写一封信。我相信有人会欣赏它... :-)
回答by iluxa
One seconds contains 1,000,000,000 nanoseconds, so as long as your number is in that range, it's reasonable.
一秒包含 1,000,000,000 纳秒,因此只要您的数字在该范围内,就是合理的。
回答by styler1972
If you want it in fractional form, just take your value
/ 10^9 where value
is your difference in nanoTime()
s.
如果您想要小数形式,只需将您的value
/ 10^9value
放在nanoTime()
s 中的差值处。
long nanoSeconds = 500000000;
float seconds = nanoSeconds / 1000000000;
Log.i("NanoTime", nanoSeconds + " ns is the same as " + seconds + " seconds");
Your output would be:
您的输出将是:
07-27 11:35:47.196: INFO/NanoTime(14237): 500000000 ns is the same as 0.5 seconds