Background

Sometimes we need to record the execution time of each task when doing development, or record the execution time of a piece of code, the simplest way is to print the difference between the current time and the execution time, and then if the implementation of a large number of tests is very troublesome, and not intuitive, if you want to do further control of the execution time, it is necessary to modify many places in the program. Currently spring-framework provides a StopWatch class can do similar task execution time control, that is, encapsulated a start time, end time record tool.

Examples

Let’s look at some examples

Total time spent

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import org.springframework.util.StopWatch;
 
public class SpringStopWatchExample {
 
    public static void main (String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start();
        //long task simulation
        Thread.sleep(1000);
        sw.stop();
        System.out.println(sw.getTotalTimeMillis());
    }
}

// Output

1013

Time consumption of the last task

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class SpringStopWatchExample2 {
 
    public static void main (String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start("A");//setting a task name
        //long task simulation
        Thread.sleep(1000);
        sw.stop();
        System.out.println(sw.getLastTaskTimeMillis());
    }
}

// output

1009

Output the time spent on all tasks in an elegant format and as a percentage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import org.springframework.util.StopWatch;
 
public class SpringStopWatchExample3 {
 
    public static void main (String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start("A");
        Thread.sleep(500);
        sw.stop();
        sw.start("B");
        Thread.sleep(300);
        sw.stop();
        sw.start("C");
        Thread.sleep(200);
        sw.stop();
        System.out.println(sw.prettyPrint());
    }
}

// output

StopWatch '': running time (millis) = 1031
-----------------------------------------
ms     %     Task name
-----------------------------------------
00514  050%  A
00302  029%  B
00215  021%  C

More Usage

Different print results

  1. getTotalTimeSeconds() gets the total elapsed time in seconds, but also has a method to get milliseconds
  2. prettyPrint() prints the results in an elegant format, in a table
  3. shortSummary() return a short description of the total elapsed time
  4. getTaskCount() return the number of statistical time tasks
  5. getLastTaskInfo().getTaskName() returns the name of the last task TaskInfo object

See more at Documentation

Summary

It is recommended that everyone use this elegant way to count the efficiency of code execution.

Reference https://ningyu1.github.io/20190505/116-stop-watch.html