且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

System.nanoTime / System.currentTimeMillis = 107(这应该是1e6吗?)

更新时间:2023-10-22 23:48:52

System.nanoTime()有一个任意的起点;这不是unix时代。 来自Javadoc

System.nanoTime() has an arbitrary start point; it's not unix epoch. From the Javadoc:


返回的值表示纳秒,因为某些固定但任意的原始时间

The value returned represents nanoseconds since some fixed but arbitrary origin time

所以你实际计算的是:

(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

Ideone demo

所以,非常接近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.