How do I calculate the elapsed time of an event in java? [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-17 04:26:49

问题


What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?


回答1:


I would avoid using System.currentTimeMillis() for measuring elapsed time. currentTimeMillis() returns the 'wall-clock' time, which may change (eg: daylight savings, admin user changing the clock) and skew your interval measurements.

System.nanoTime(), on the other hand, returns the number of nanoseconds since 'some reference point' (eg, JVM start up), and would therefore not be susceptible to system clock changes.




回答2:


This is some sample code.

long startTime = System.currentTimeMillis();
// Run some code;
long stopTime = System.currentTimeMillis();

System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds.");



回答3:


Apache Commons-Lang also has the StopWatch class suited just for your purpose. It uses System.currentTimeMillis(), so you'll still have resolution problems, but you can pause and do lap times and such. I use it as standard now for event stats.

http://commons.apache.org/lang/api-release/org/apache/commons/lang/time/StopWatch.html




回答4:


The Answer by Leigh is correct.

java.time

Java 8 and later has the java.time framework built in.

An Instant is a moment on the timeline in UTC with nanosecond resolution (up to 9 digits of a decimal fraction of a second). The now method grabs the current date-time moment.

Instant now = Instant.now();

2016-03-12T04:29:39.123Z

You can calculate the elapsed time between a pair of Instant objects as a Duration. The duration uses nanosecond resolution with a maximum value of the seconds that can be held in a long. This is greater than the current estimated age of the universe.

Duration duration = Duration.between( startInstant , stopInstant );

The default output of Duration::toString is in standard ISO 8601 format. You can also ask for a total count of nanoseconds (toNanos) or milliseconds (toMillis), as well as other amounts.

Java 8

In Java 8, fetching the current moment resolves only to millisecond resolution (up to 3 digits of a decimal fraction of a second). So while the java.time classes can store nanoseconds they can only determine the current moment with milliseconds. This limitation is due to a legacy issue (the default Clock implementation uses System.currentTimeMillis()).

Java 9

In Java 9 and later, the default Clock implementation can determine the current moment in up to nanosecond resolution. Actually doing so depends on the fineness of your computer’s clock hardware.

See this OpenJDK issue page for more info: Increase the precision of the implementation of java.time.Clock.systemUTC()

Micro Benchmark

If your purpose is benchmarking, be sure to look at other Questions such as:

  • How do I write a correct micro-benchmark in Java?
  • Create quick/reliable benchmark with java?

Frameworks are available to assist with short-duration benchmarking.




回答5:


java.lang.System.currentTimeMillis() or java.lang.System.nanoTime() ought to work to measure elapsed time.




回答6:


Here is a small StopWatch class I wrote using the System.nanoTime() as suggested in the answer from Leigh:

public class StopWatch {
    // Constructor
    public StopWatch() {
    }

    // Public API
    public void start() {
        if (!_isRunning) {
            _startTime = System.nanoTime();
            _isRunning = true;
        }
    }

    public void stop() {
        if (_isRunning) {
            _elapsedTime += System.nanoTime() - _startTime;
            _isRunning = false;
        }
    }

    public void reset() {
        _elapsedTime = 0;
        if (_isRunning) {
            _startTime = System.nanoTime();
        }
    }

    public boolean isRunning() {
        return _isRunning;
    }

    public long getElapsedTimeNanos() {
        if (_isRunning) {
            return System.nanoTime() - _startTime;
        }
        return _elapsedTime;
    }

    public long getElapsedTimeMillis() {
        return getElapsedTimeNanos() / 1000000L;
    }

    // Private Members
    private boolean _isRunning = false;
    private long _startTime = 0;
    private long _elapsedTime = 0;
}


来源:https://stackoverflow.com/questions/238920/how-do-i-calculate-the-elapsed-time-of-an-event-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!