1

I want to compare the performance of certain operations in my application.

Other than using the Date object, is there anything more precise?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

3 Answers3

7

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.

Community
  • 1
  • 1
Yada
  • 30,349
  • 24
  • 103
  • 144
  • 1
    No, it hasn't only millisecond precision. They access the much more accurate media timer in Java if possible with much more resolution. – Thorsten S. Jan 19 '10 at 21:53
  • Nano time is not very precise, because it's not updated every nanosecond, like @ThorstenS.mentioned, it has about a millisecond resolution. In my case, using currentTimeMillis() was better choice because nanoTime() had weird "lag spikes". – rainisr Jun 27 '19 at 07:28
2

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.

Kevin Bourrillion
  • 40,336
  • 12
  • 74
  • 87
  • Nano time is not very precise, because it's not updated every nanosecond, like @ThorstenS.mentioned, it has about a millisecond resolution. In my case, using currentTimeMillis() was better choice because nanoTime() had weird "lag spikes". – rainisr Jun 27 '19 at 07:28
2

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.

user85421
  • 28,957
  • 10
  • 64
  • 87