zoukankan      html  css  js  c++  java
  • 优雅计时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;
        }
    }
    
  • 相关阅读:
    YARN的job提交流程
    shell脚本学习(二)
    解决document.getElementById("")在IE7中误读成name的bug
    类数组对象HTMLCollenction
    NodeList对象的特点
    复习周期不能太长!!!
    递归 / 前端零基础入门 2019版 / 步骤五 · 3-6 节点遍历案例
    节点查找以及节点遍历:两种方式
    判断是否是IE浏览器
    html5shiv主要解决IE6-8 无法识别HTML5的新标签,父节点不能包裹子元素,以及应用CSS样式
  • 原文地址:https://www.cnblogs.com/zhangjianbing/p/15554035.html
Copyright © 2011-2022 走看看