How can I measure time with microsecond precision in Java?

前端 未结 12 895
死守一世寂寞
死守一世寂寞 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 02:12

    It's not clear to me exactly what you're benchmarking, but in general, any test which takes such a short amount of time to run, that accuracy lower than 50 ms is relevant, is going to be very prone to other disturbances.

    I generally try to make benchmarks run for at least 10 seconds. The framework I'm writing at the moment will guess how many iterations to run so that it will take 30 seconds. That means you won't get radically different results just because some other process stole the CPU for a few milliseconds.

    Running for longer is almost always a better approach than trying to measure with finer-grained accuracy.

提交回复
热议问题