ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

优雅计时StopWatch

2021-11-14 23:31:38  阅读:173  来源: 互联网

标签:sw void stop System 优雅 start 计时 StopWatch


在程序中要对某一段业务逻辑进行计时,一般采用如下方法来统计耗时:

public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    doSomeThing();
    long endTime = System.currentTimeMillis();
    long totalTime = (endTime - startTime) / 1000;
    System.out.println("总共耗时:" + totalTime + "s");
}

private static void doSomeThing() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

这种方式没毛病,还有一个工具类可以参考下,它叫StopWatch。使用方式介绍:

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

输出内容:

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

注意:StopWatch要引SpringFramework的,不要引lang3的包。原理就是把StopWatch的start到stop这块代码计算好时间后,放到LinkedList中,当调用prettyPrint的时候,再格式化打印。在异步线程使用的时候,子线程一定要新new StopWatch(),否则统计不上。附上源码:

public void start(String taskName) throws IllegalStateException {
    if (this.currentTaskName != null) {
        throw new IllegalStateException("Can't start StopWatch: it's already running");
    } else {
        this.currentTaskName = taskName;
        this.startTimeMillis = System.currentTimeMillis();
    }
}

public void stop() throws IllegalStateException {
    if (this.currentTaskName == null) {
        throw new IllegalStateException("Can't stop StopWatch: it's not running");
    } else {
        long lastTime = System.currentTimeMillis() - this.startTimeMillis;
        this.totalTimeMillis += lastTime;
        this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime);
        if (this.keepTaskList) {
            this.taskList.add(this.lastTaskInfo);
        }

        ++this.taskCount;
        this.currentTaskName = null;
    }
}

标签:sw,void,stop,System,优雅,start,计时,StopWatch
来源: https://www.cnblogs.com/zhangjianbing/p/15554035.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有