StopWatch任务计时器

介   绍:

    StopWatch 是用来计算程序块的执行时间工具, 目前有好多框架都有实现提供此工具(实现结果都区别不大), 本文介绍org.springframework.util.StopWatch

应用背景:

     在开发过程中,有时候我们需要判断程序的执行时间来定位是哪个模块的执行效率比较低;例如: 有一个方法在处理计算结果时,返回的时间很长,这个时候就需要判断这个方法中的哪一段代码执行时间比较长,就可以使用StopWatch工具来计算时间,从而更好的定位问题;

demo :

    

public static void demo2() throws Exception{
        
        //构建StopWatch实例
        org.springframework.util.StopWatch stopWatch = new org.springframework.util.StopWatch();
        
        //开始第一个计时任务, start(taskName) ---> taskName指任务名称
        stopWatch.start("第一个计时任务----for循环执行时间");
        for(int i = 0; i < 100000; i++){
            for(int j = 0; j < 1000000; j++){
            }
        }
        //计算for循环执行的时间,需要调用stop()方法停止计时
        stopWatch.stop();
        
        
        //第二个计时任务
        stopWatch.start("第二个计时任务----休眠2S");
        Thread.sleep(2000);
        stopWatch.stop();  
        
        //......
        
        //得到所有任务的计时结果
        String prettyPrint = stopWatch.prettyPrint();   
        
        System.out.println(prettyPrint);
        
    }

执行结果:

原文地址:https://www.cnblogs.com/whqworld/p/10569662.html