How can I measure time with microsecond precision in Java?

前端 未结 12 915
死守一世寂寞
死守一世寂寞 2020-12-03 01:15

I saw on the Internet that I was supposed to use System.nanoTime() but that doesn\'t work for me - it gives me the time with milliseconds precision. I just need

12条回答
  •  醉话见心
    2020-12-03 01:49

    Yes, the accuracy and precision of System.nanoTime is usually much better than System.currentTimeMillis, but without guarantee: it can become just as bad in the worst case.

    ThreadMXBean.getCurrentThreadCpuTime tends to yield smaller times, but its resolution is unclear, and it has further disadvantages (do you really want the CPU time?, platform dependent semantics, supported on your platform?).

    Measuring the time with all three techniques also has some cost, i.e. requires time itself, which can distort the measurements. The costs are highly platform dependent, but often cost(System.currentTimeMillis) << cost(System.nanoTime) << cost(ThreadMXBean.getCurrentThreadCpuTime).

    About micro benchmarking in general, see

    • How do I write a correct micro-benchmark in Java?
    • Create quick/reliable benchmark with java?

提交回复
热议问题