How can I measure time in Java not susceptible to System clock changes?

后端 未结 5 781
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 10:43

I would like to measure elapsed time in a Java. However differences in System.currentTimeMillis() and (I believe) System.nanoTime() can be changed

5条回答
  •  旧巷少年郎
    2021-01-03 11:36

    If you don't mind adding a bit of native code to your Java app, use:

    • QueryPerformanceCounter() and QueryPerformanceFrequency() on Windows; or

    • POSIX clock_gettime() function with CLOCK_MONOTONIC clock ID.

    Note that the use of the x86 TSC register is discouraged on multiprocessor systems, so you better use the above APIs.

提交回复
热议问题