Precise time measurement in Java

后端 未结 5 867
说谎
说谎 2021-02-07 07:28

Java gives access to two method to get the current time: System.nanoTime() and System.currentTimeMillis(). The first one gives a result in nanoseconds,

5条回答
  •  既然无缘
    2021-02-07 07:52

    Unfortunately, I don't think java RTS is mature enough at this moment.

    Java time does try to provide best value (they actually delegate the native code to call get the kernal time). However, JVM specs make this coarse time measurement disclaimer mainly for things like GC activities, and support of underlying system.

    • Certain GC activities will block all threads even if you are running concurrent GC.
    • default linux clock tick precision is only 10ms. Java cannot make it any better if linux kernal does not support.

    I haven't figured out how to address #1 unless your app does not need to do GC. A decent and med size application probably and occasionally spends like tens of milliseconds on GC pauses. You are probably out of luck if your precision requirement is lower 10ms.

    As for #2, You can tune the linux kernal to give more precision. However, you are also getting less out of your box because now kernal context switch more often.

    Perhaps, we should look at it different angle. Is there a reason that OPS needs precision of 10ms of lower? Is it okay to tell Ops that precision is at 10ms AND also look at the GC log at that time, so they know the time is +-10ms accurate without GC activity around that time?

提交回复
热议问题