Accurate time measurement (Java)

Method

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));

Comparison with currentTimeMillis ()

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

Accurate time measurement (Java)
[Java] Processing time measurement method memo
Java coverage measurement library
Processing time measurement for each BCrypt + stretch count in Java
Handling of time zones using Java
Java
[MySQL] [java] Receive date and time
Java
Memory measurement for Java apps using jstat
Introduction to java for the first time # 2
Convert from java UTC time to JST time
[Java] How to measure program execution time
[Java] How to set the Date time to 00:00:00
Java 8 to start now ~ Date time API ~
Compare Android Java dates only (excluding time)
Learning for the first time java [Introduction]
Memory measurement of Java application on Windows
java Calendar class (time set, comparison, format)