为什么System.nanoTime()比System.currentTimeMillis()慢(性能)? [英] Why is System.nanoTime() way slower (in performance) than System.currentTimeMillis()?

查看:267
本文介绍了为什么System.nanoTime()比System.currentTimeMillis()慢(性能)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Today I did a little quick Benchmark to test speed performance of System.nanoTime() and 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

为什么运行速度的差异如此之大?

Why are the differences in running speed so big?

基准系统:

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


推荐答案

来自此Oracle博客


System.currentTimeMillis()使用
GetSystemTimeAsFileTime方法实现,该方法基本上只读取Windows维护的低
分辨率时间值。根据
报告的信息,读取这个
全局变量自然非常快 - 大约6个周期。

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.

使用
QueryPerformanceCounter / QueryPerformanceFrequency实现System.nanoTime() API
(如果可用,
否则返回 currentTimeMillis * 10 ^ 6)
QueryPerformanceCounter(QPC)以不同的方式实现
,具体取决于它运行的硬件。通常,它将使用
可编程间隔定时器(PIT)或ACPI电源
管理定时器(PMT)或CPU级时间戳计数器(TSC)。
访问PIT / PMT需要执行慢速I / O端口指令
,因此QPC的执行时间大约为
微秒。相反,读取TSC大约为100个时钟
周期(从芯片读取TSC并根据工作频率将其转换为时间值
)。

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).

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

Perhaps this answer the question. The two methods use different number of clock cycles, thus resulting in slow speed of the later one.

在结论部分的博客中进一步说明:

Further in that blog in the conclusion section:


如果您对测量/计算已用时间感兴趣,请始终使用System.nanoTime()。在大多数系统上,它将提供微秒级的分辨率。请注意,此调用在某些平台上也可能需要几微秒才能执行

这篇关于为什么System.nanoTime()比System.currentTimeMillis()慢(性能)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆