用Java衡量经过时间的最快方法 [英] Fastest way to measure elapsed time in Java

查看:118
本文介绍了用Java衡量经过时间的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所读到的有关currentTimeMillis vs nanoTime的所有内容似乎都只关注准确性.如果我仅以毫秒为单位查找经过的时间,那么如果我想获得最佳性能应该使用哪一个时间?

Everything I've read about currentTimeMillis vs nanoTime seem to only focus on accuracy. If I'm only looking for elapsed time in milliseconds, which one of these should I use if I want the best performance?

似乎像currentTimeMillis就是答案,因为我不需要将最终答案从ns转换为ms,但这是从我的应用程序的角度来看,在幕后进行的事情可能会使它成为错误的选择,这是我为什么要问.

Seems like currentTimeMillis would be the answer, since I don't need to convert the final answer from ns to ms, but that's from my application's perspective, and what goes on under the hood could make it the wrong choice, which is why I'm asking.

推荐答案

在纯Java中,基本上只有两个选项:您已经命名了它们:

There are basically just two options in pure Java; you've already named them:

  • System.currentTimeMillis
  • System.nanoTime
  • System.currentTimeMillis
  • System.nanoTime

这两种方法都是JVM内在函数.
在Linux上,它们被编译成直接调用 gettimeofday 或分别 clock_gettime .
在Windows上- GetSystemTimeAsFileTime 或分别 QueryPerformanceCounter .

Both methods are JVM intrinsics.
On Linux they are compiled into direct calls to gettimeofday or clock_gettime respectively.
On Windows - GetSystemTimeAsFileTime or QueryPerformanceCounter respectively.

这些方法的性能在很大程度上取决于平台,CPU体系结构,操作系统版本,Java版本,并发线程数等.在我的Windows笔记本电脑上,currentTimeMillis花费7 ns,而nanoTime-16 ns,而在多处理器Linux服务器上,这两种方法花费大约40 ns.因此,这取决于.

The performance of these methods highly depends on the platform, CPU architecture, OS version, Java version, number of concurrent threads etc. E.g. on my Windows Laptop currentTimeMillis takes 7 ns, and nanoTime - 16 ns, while on multiprocessor Linux server both methods take about 40 ns. So, it depends.

我强烈建议阅读AlexeyShipilёv的帖子 纳米信任纳米时间 涵盖了Java时间测量的许多方面.

I highly recommend to read Alexey Shipilёv's post Nanotrusting the nanotime covering many aspects of time measurements in Java.

这篇关于用Java衡量经过时间的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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