How can I measure time with microsecond precision in Java?

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

    System.nanoTime() uses a counter in the CPU and is usually accurate to about 1 micro-second on Windows XP and Linux.

    Note: Windows XP is often less accurate on multi-cpu machines as it doesn't compensate for different CPUs having different counters. Linux does. Note 2: It will drift relative to the System.currentTimeMillis() as it is based on the accuracy of the clock for your CPU (which doesn't need to be so accurate over a period of time), rather than the clock you have for getting the time.(which drifts less per day, but has less granularity)

    In your benchmark you are basically testing the speed at which you can create new objects. Not surprisingly your results will vary dramatically based on your GC settings and how recently a GC has been performed.

    Try running your tests with the following options and you should see very different results.

    -verbosegc -XX:NewSize=128m -mx256m
    

提交回复
热议问题