How can I measure time with microsecond precision in Java?

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

    a "quick and dirty" solution that I eventually went with:

    TimeUnit.NANOSECONDS.toMicros(System.nanoTime());
    

    UPDATE:

    I originally went with System.nanoTime but then I found out it should only be used for elapsed time, I eventually changed my code to work with milliseconds or at some places use:

    TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
    

    but this will just add zeros at the end of the value (micros = millis * 1000)

    Left this answer here as a "warning sign" in case someone else thinks of nanoTime :)

提交回复
热议问题