For java programmers, the time format will always make people scratch their heads to see the Java Date Time tutorial-time measurement

In Java, it is most convenient to use System.currentTimeMillis() to measure time. What you have to do is get the time before certain operations, and then after these operations you want to measure the time and calculate the time difference. Below is an example:

long startTime = System.currentTimeMillis();
callOperationToTime();
long endTime   = System.currentTimeMillis();
long totalTime = endTime - startTime;

Now the variable totalTime will contain all the time required to execute the callOperationToTime() method.

Repeat operation

Since System.currentTimeMillis() does not return an accurate time, it is a good idea to perform the measurement operation more than once. Maybe 10 times, 100 times, 1000 times, or more. In this way, the inaccurate time caused by the large-granularity time value (the value does not change every millisecond) will stabilize. Another good reason to perform many measurement operations repeatedly is to allow the Java virtual machine to load the classes of the measurement operation code, compile it on the fly, and perhaps optimize it.

Timer class

The calculation method listed above is quite cumbersome and boring. We can encapsulate it in a Timer class. The following is a rough example:

public class Timer {

  private long startTime = 0;
  private long endTime   = 0;

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

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

  public long getStartTime() {
    return this.startTime;
  }

  public long getEndTime() {
    return this.endTime;
  }

  public long getTotalTime() {
    return this.endTime - this.startTime;
  }
}

Here is an example of how to use the Timer class:

Timer timer = new Timer();
timer.start();
callOperationToTime();
timer.end();
long totalTime = timer.getTotalTime();

The above is all the content of this article. If you need to receive java learning materials, private message reply materials, receive first-line Java interview questions summary + Alibaba Taishan manual + learning thinking guide for each knowledge point + a 300-page pdf document Java core knowledge points to sum up!

The content of these materials are all the knowledge points that the interviewer must ask during the interview. The chapter includes many knowledge points, including basic knowledge, Java collections, JVM, multi-threaded concurrency, spring principles, microservices, Netty and RPC, Kafka , Diary, design pattern, Java algorithm, database, Zookeeper, distributed cache, data structure, etc. file

Guess you like

Origin blog.csdn.net/weixin_46577306/article/details/108109433