自学内容网 自学内容网

Java小抄|使用StopWatch输出执行耗时

背景

StopWatch是spring-framwork提供的一个可以对任务执行时间进行控制的类,方便记录任务的开始时间和结束时间

常用接口定义

  • getTotalTimeSeconds() 获取总耗时秒,同时也有获取毫秒的方法
  • prettyPrint() 优雅的格式打印结果,表格形式
  • shortSummary() 返回简短的总耗时描述
  • getTaskCount() 返回统计时间任务的数量
  • getLastTaskInfo().getTaskName() 返回最后一个任务TaskInfo对象的名称

demo1 统计输出的总耗时

public static void main(String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start();
        Thread.sleep(1000);
        sw.stop();
        System.out.println(sw.getTotalTimeMillis());
        Thread.sleep(1000);
        System.out.println(sw.getTotalTimeMillis());
    }

image.png
从两次都是1005的结果可以看出,获取任务总耗时的时候,需要关心的是stopwatch开始和结束的时间节点,并不是打印耗时的时间节点

demo2 统计最后一个任务的耗时

public static void main (String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start("A");
        Thread.sleep(1000);
        sw.stop();
        System.out.println(sw.getLastTaskTimeMillis());
        sw.start("B");
        Thread.sleep(500);
        sw.stop();
        System.out.println(sw.getLastTaskTimeMillis());
    }

image.png

demo3 统计多个任务的耗时占比

public static void main (String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start("A");
        Thread.sleep(1000);
        sw.stop();
        System.out.println(sw.prettyPrint());
        sw.start("B");
        Thread.sleep(500);
        sw.stop();
        System.out.println(sw.prettyPrint());
    }

#image.png


原文地址:https://blog.csdn.net/weixin_44435110/article/details/140726571

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!