StopWatch gracefully replaces currentTimeMillis calculation program execution time

  • 2021-11-14 05:34:49
  • OfStack

Demand

Sometimes it is necessary to record the execution time of the program. The simplest thing is to print the difference between the current time and the execution time. The disadvantages are:

It is very troublesome to perform a lot of tests Not intuitive If you want to control the execution time one step further, you need to modify many places in the program

Therefore, Spring provides an StopWatch class that can control the execution time of similar tasks, that is, it encapsulates a tool for recording the start time and end time

Case

Statistical output total time consumption


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 the time spent on the last 1 task


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

Type the time consumption and proportion of all tasks in an elegant format


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

Sequence service output time-consuming information


@Override
public long nextSeq(String name) {
    StopWatch watch = new StopWatch();
    watch.start(" Total consumption of single sequence acquisition ");
    long sequence = generator.generateId(name);
    watch.stop();
    logger.info(watch.prettyPrint());
    return sequence;
}

getTotalTimeSeconds () takes a total of seconds to get, and there is also a way to get milliseconds
prettyPrint () Elegant format printing results, tabular form
shortSummary () returns a brief description of the total time spent
getTaskCount () returns the number of statistical time tasks
getLastTaskInfo (). getTaskName () Returns the name of the last task TaskInfo object


Related articles: