问题描述
根据
nanoTime ()返回正在运行的Java Virtual
Machine的高分辨率时间源的当前值,以纳秒为单位。
nanoTime() Returns the current value of the running Java Virtual Machine's high resolution time source, in nanoseconds.
严格来说纳秒为1e-9,毫秒为1e-3。因此,纳秒的持续时间必须是相同持续时间的1e6的倍数(以毫秒为单位)。实际情况并非如此,原因是什么?
Strictly speaking a nanosecond is 1e-9 and millisecond is 1e-3. Therefore, a duration in nanosecs must be a multiple of 1e6 of the same duration in millisecs. This is not the case in practice, what is the reason?
scala> System.nanoTime / System.currentTimeMillis
res0: Long = 107
推荐答案
System.nanoTime()
有一个任意的起点;这不是unix时代。 :
System.nanoTime()
has an arbitrary start point; it's not unix epoch. From the Javadoc:
所以你实际计算的是:
(unknownOffset + offsetFromEpochInNanos) / offsetFromEpochInMillis
几乎肯定不是1e6,除非 unknownOffset
发生任意归零。
which will almost certainly not be 1e6, unless unknownOffset
happens to be arbitrarily zero.
如果你可以通过减去两次来消除未知偏移的影响,你可以看到该比率大约为1e6:
If you can remove the effect of the unknown offset by subtracting the two times, you can see that the ratio is around 1e6:
long nanoStart = System.nanoTime();
long milliStart = System.currentTimeMillis();
Thread.sleep(2000);
long nanoEnd = System.nanoTime();
long milliEnd = System.currentTimeMillis();;
long nanoDelta = nanoEnd - nanoStart;
long milliDelta = milliEnd - milliStart;
System.out.println((double) nanoDelta / milliDelta);
输出(运行5次):
1000058.3725
1000045.4705
999549.1579210395
1000046.101
1000038.1045
所以,非常接近1e6。
So, pretty close to 1e6.
注意可能不是这个,因为 System.currentTimeMillis()
由于时钟偏差的修正而无法顺利进行。但是,这些应该是不常见的,所以大部分时间当你运行这段代码时,你会看到大约1e6。
Note that it might not be this, because System.currentTimeMillis()
doesn't progress smoothly, owing to corrections for clock skew. However, these should be infrequent, so most of the time when you run this code, you'll see roughly 1e6.
这篇关于System.nanoTime / System.currentTimeMillis = 107(这应该是1e6吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!