gpt4 book ai didi

java - 为什么 System.nanoTime() 比 System.currentTimeMillis() 慢(在性能上)?

转载 作者:IT老高 更新时间:2023-10-28 13:54:06 26 4
gpt4 key购买 nike

今天我做了一个快速的 Benchmark 来测试 System.nanoTime()System.currentTimeMillis() 的速度性能:

long startTime = System.nanoTime();

for(int i = 0; i < 1000000; i++) {
long test = System.nanoTime();
}

long endTime = System.nanoTime();

System.out.println("Total time: "+(endTime-startTime));

这是结果:

System.currentTimeMillis(): average of 12.7836022 / function call
System.nanoTime(): average of 34.6395674 / function call

为什么运行速度差异这么大?

基准系统:

Java 1.7.0_25
Windows 8 64-bit
CPU: AMD FX-6100

最佳答案

来自 this Oracle blog :

System.currentTimeMillis() is implemented using the GetSystemTimeAsFileTime method, which essentially just reads the low resolution time-of-day value that Windows maintains. Reading this global variable is naturally very quick - around 6 cycles according to reported information.

System.nanoTime() is implemented using the QueryPerformanceCounter/ QueryPerformanceFrequency API (if available, else it returns currentTimeMillis*10^6). QueryPerformanceCounter(QPC) is implemented in different ways depending on the hardware it's running on. Typically it will use either the programmable-interval-timer (PIT), or the ACPI power management timer (PMT), or the CPU-level timestamp-counter (TSC). Accessing the PIT/PMT requires execution of slow I/O port instructions and as a result the execution time for QPC is in the order of microseconds. In contrast reading the TSC is on the order of 100 clock cycles (to read the TSC from the chip and convert it to a time value based on the operating frequency).

也许这回答了这个问题。这两种方法使用的时钟周期数不同,从而导致后一种速度较慢。

在该博客的结论部分进一步:

If you are interested in measuring/calculating elapsed time, then always use System.nanoTime(). On most systems it will give a resolution on the order of microseconds. Be aware though, this call can also take microseconds to execute on some platforms.

关于java - 为什么 System.nanoTime() 比 System.currentTimeMillis() 慢(在性能上)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19052316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com