Home >Java >javaTutorial >How Can I Accurately Measure Elapsed Time in Java?

How Can I Accurately Measure Elapsed Time in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-31 12:14:14817browse

How Can I Accurately Measure Elapsed Time in Java?

Measuring Time Elapsed in Java

In Java, measuring elapsed time accurately requires understanding the distinction between elapsed time and wall-clock time. While many responses suggest using System.currentTimeMillis(), it is crucial to note that it measures wall-clock time, which can be affected by clock corrections.

To measure elapsed time correctly, System.nanoTime() should be used. This API is specifically designed to quantify elapsed time and remains unaffected by clock corrections. Therefore, it provides more accurate readings than System.currentTimeMillis().

Regarding your sample code, to capture the elapsed duration between startTime and endTime, you can use the following approach:

public class Stream {
    private long startTime;
    private long endTime;

    public void start() {
        startTime = System.nanoTime();
    }

    public void end() {
        endTime = System.nanoTime();
    }

    public long getDuration() {
        return (endTime - startTime);
    }
}

In this example, you can modify the startTime and endTime values within the start() and end() methods when you want to commence and terminate your time measurement. The getDuration() method returns the elapsed time in nanoseconds, which can be converted to other units if desired.

Remember, for precise elapsed time measurement, it is essential to utilize System.nanoTime() and avoid relying on System.currentTimeMillis(), which is susceptible to clock corrections.

The above is the detailed content of How Can I Accurately Measure Elapsed Time in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn