Is System.currentTimeMillis() the best measure of time performance in Java?

后端 未结 7 513
别跟我提以往
别跟我提以往 2020-12-31 04:34

Is System.currentTimeMillis() the best measure of time performance in Java? Are there any gotcha\'s when using this to compare the time before action is taken to the time af

相关标签:
7条回答
  • 2020-12-31 05:03

    One gotcha is that this measures real time elapsed, not CPU time - so it is very dependent on system load. This is fine if your on an otherwise free machine, but can sometimes produce interesting results if other processes are trying to do work.

    This article has an intersting solution to the problem.

    0 讨论(0)
  • 2020-12-31 05:07

    besides System.nanoTime(), JMX is probably the best viable option:

    java.lang.management.ManagementFactory.getThreadMXBean()
    

    you can query current thread cpu time (measured in nano seconds but not with nano seconds precision, as for System.nanoTime())

    0 讨论(0)
  • 2020-12-31 05:08

    If you need monotonic time measurements, System.nanoTime is a better choice. System.currentTimeMillis is subject to UTC timing variations -- leap seconds, NTP updates and jitter, as well as users setting the system clock*. This can cause some spectacular failures in certain kinds of timing applications. System.nanoTime is supposed to be immune to all that.

    The problems with System.nanoTime include periodic numeric overflow and long term timing inaccuracy, making System.currentTimeMillis better for longer time spans (provided that users leave the system clock alone). Note that daylight saving time and time zone changes should not affect System.currentTimeMillis.

    *Windows "Sync with internet time" makes stepwise changes. This can be very disruptive, as opposed to a proper NTP client implementation that "chases" the server by adjusting the client timebase frequency.

    0 讨论(0)
  • 2020-12-31 05:09

    Before Java 1.5 there was only System.currentTimeMillis. However the granularity of the value depends on the underlying operating system and may be large. On Windows XP I sometimes ended up with gaps of 20ms. I heard Linux is way better with gaps in the range of 1-2ms.

    With Java 1.5 you can also use System.nanoTime. I never had problems with this one.

    0 讨论(0)
  • 2020-12-31 05:12

    I hope not - it's what I use when i don't use nanoTime().

    0 讨论(0)
  • 2020-12-31 05:15

    Take a look at this:

    How do I time a method's execution in Java?

    0 讨论(0)
提交回复
热议问题