Previously, the currentTimeMills () method was used to measure the time. However, when measuring processing that takes place in a very short time, it may only be possible to measure in milliseconds. Accurate time measurement is not possible. Therefore, the time is measured by the nanoTime () method, which can measure the time in nanosecond units.
long start = System.nanoTime();
//Describe the process you want to measure
long end = System.nanoTime();
long timeSeconds = TimeUnit.NANOSECONDS.toSeconds((end - start));
currentTimeMillis | nanoTime | |
---|---|---|
Feature | The number of seconds elapsed since 0:00:00 on January 1, 1970, expressed in milliseconds. | A method specialized only for time measurement. |
merit | It is thread safe.(It must be a safe method even if it is called from multiple threads.) | Since it can be measured in nanoseconds, it is possible to measure time more accurately than currentTimeMillis. |
Demerit | When measuring the time from a certain point in the past, the measurement result may shift because it does not include leap seconds. | Not thread safe. |
Recommended Posts