I wa开发者_开发技巧nt to compare the performance of certain operations in my application.
Other than using the Date object, is there anything more precise?
public static long nanoTime()
- Returns the current value of the most precise available system timer, in nanoseconds.
As Zach Scrivener states in his answer:
My guess is that since System.nanoTime() uses the "most precise available system timer" which apparently only has millisecond-precision on your system, you can't get anything better.
If you're measuring elapsed time by subtracting two timestamps, you should use System.nanoTime()
to get those timestamps. That's what it's for.
To get the CPU time you can use the getCurrentThreadCpuTime
of the Thread Management Bean.
It returns the CPU time used by the actual thread in nanoseconds:
ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
long time = threadMX.getCurrentThreadCpuTime();
// do something
time = threadMX.getCurrentThreadCpuTime() - time; // CPU time in nanoseconds
check the documentation for details and some problems like CPU time measurement not being enabled.
精彩评论