问题
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?
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.
回答1:
There are basically just two options in pure Java; you've already named them:
System.currentTimeMillis
System.nanoTime
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.
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.
I highly recommend to read Alexey Shipilёv's post Nanotrusting the nanotime covering many aspects of time measurements in Java.
回答2:
You shouldn't use currentTimeMillis, always use nanoTime for measuring elapsed time. Actually using currentTimeMillis could yield a negative result. This is because it uses the system clock, which is adjusted (sometimes it goes backwards) to the time at your timezone. The nanoTime method uses a clock started by the JVM that is used precisely for timing.
来源:https://stackoverflow.com/questions/40250112/fastest-way-to-measure-elapsed-time-in-java