欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring计时器stopwatch使用详解

程序员文章站 2022-06-26 11:25:40
 stopwatch是位于org.springframework.util包下的一个工具类,通过它可方便的对程序部分代码进行计时(ms级别),适用于同步单线程代码块。正常情况下,我们如果需...

 stopwatch是位于org.springframework.util包下的一个工具类,通过它可方便的对程序部分代码进行计时(ms级别),适用于同步单线程代码块。
正常情况下,我们如果需要看某段代码的执行耗时,会通过如下的方式进行查看:

public static void main(string[] args) throws interruptedexception {
     stopwatchtest.test0();
//        stopwatchtest.test1();
}

public static void test0() throws interruptedexception {
     long start = system.currenttimemillis();
     // do something
     thread.sleep(100);
    long end = system.currenttimemillis();
    long start2 = system.currenttimemillis();
    // do something
    thread.sleep(200);
    long end2 = system.currenttimemillis();
    system.out.println("某某1执行耗时:" + (end - start));
    system.out.println("某某2执行耗时:" + (end2 - start2));
}
运行结果:
某某1执行耗时:105
某某2执行耗时:203

    该种方法通过获取执行完成时间与执行开始时间的差值得到程序的执行时间,简单直接有效,但想必写多了也是比较烦人的,尤其是碰到不可描述的代码时,会更加的让人忍不住多写几个bug聊表敬意,而且该结果也不够直观,此时会想是否有一个工具类,提供了这些方法,或者自己写个工具类,刚好可以满足这种场景,并且把结果更加直观的展现出来。
首先我们的需求如下:

  1. 记录开始时间点
  2. 记录结束时间点
  3. 输出执行时间及各个时间段的占比

 根据该需求,我们可直接使用org.springframework.util包下的一个工具类stopwatch,通过该工具类,我们对上述代码做如下改造:

public static void main(string[] args) throws interruptedexception {
//        stopwatchtest.test0();
     stopwatchtest.test1();
}

public static void test1() throws interruptedexception {
     stopwatch sw = new stopwatch("test");
     sw.start("task1");
     // do something
    thread.sleep(100);
    sw.stop();
    sw.start("task2");
    // do something
    thread.sleep(200);
    sw.stop();
    system.out.println("sw.prettyprint()~~~~~~~~~~~~~~~~~");
    system.out.println(sw.prettyprint());
}
运行结果:
sw.prettyprint()~~~~~~~~~~~~~~~~~
stopwatch 'test': running time (millis) = 308
-----------------------------------------
ms     %     task name
-----------------------------------------
00104  034%  task1
00204  066%  task2

 start开始记录,stop停止记录,然后通过stopwatch的prettyprint方法,可直观的输出代码执行耗时,以及执行时间百分比,瞬间感觉比之前的方式高大上了一个档次。
除此之外,还有以下两个方法shortsummary,gettotaltimemillis,查看程序执行时间。
运行代码及结果:

system.out.println("sw.shortsummary()~~~~~~~~~~~~~~~~~");
system.out.println(sw.shortsummary());
system.out.println("sw.gettotaltimemillis()~~~~~~~~~~~~~~~~~");
system.out.println(sw.gettotaltimemillis());
运行结果
sw.shortsummary()~~~~~~~~~~~~~~~~~
stopwatch 'test': running time (millis) = 308
sw.gettotaltimemillis()~~~~~~~~~~~~~~~~~
308

 其实以上内容在该工具类中实现也极其简单,通过start与stop方法分别记录开始时间与结束时间,其中在记录结束时间时,会维护一个链表类型的tasklist属性,从而使该类可记录多个任务,最后的输出也仅仅是对之前记录的信息做了一个统一的归纳输出,从而使结果更加直观的展示出来。
stopwatch优缺点:
优点:

  1. spring自带工具类,可直接使用
  2. 代码实现简单,使用更简单
  3. 统一归纳,展示每项任务耗时与占用总时间的百分比,展示结果直观性能消耗相对较小,并且最大程度的保证了start与stop之间的时间记录的准确性
  4. 可在start时直接指定任务名字,从而更加直观的显示记录结果

缺点:

  1. 一个stopwatch实例一次只能开启一个task,不能同时start多个task,并且在该task未stop之前不能start一个新的task,必须在该task stop之后才能开启新的task,若要一次开启多个,需要new不同的stopwatch实例
  2. 代码侵入式使用,需要改动多处代码

spring中stopwatch源码实现如下:

import java.text.numberformat;
import java.util.linkedlist;
import java.util.list;

public class stopwatch {
    private final string id;
    private boolean keeptasklist = true;
    private final list<taskinfo> tasklist = new linkedlist();
    private long starttimemillis;
    private boolean running;
    private string currenttaskname;
    private stopwatch.taskinfo lasttaskinfo;
    private int taskcount;
    private long totaltimemillis;

    public stopwatch() {
        this.id = "";
    }

    public stopwatch(string id) {
        this.id = id;
    }

    public void setkeeptasklist(boolean keeptasklist) {
        this.keeptasklist = keeptasklist;
    }

    public void start() throws illegalstateexception {
        this.start("");
    }

    public void start(string taskname) throws illegalstateexception {
        if (this.running) {
            throw new illegalstateexception("can't start stopwatch: it's already running");
        } else {
            this.starttimemillis = system.currenttimemillis();
            this.running = true;
            this.currenttaskname = taskname;
        }
    }

    public void stop() throws illegalstateexception {
        if (!this.running) {
            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.running = false;
            this.currenttaskname = null;
        }
    }

    public boolean isrunning() {
        return this.running;
    }

    public long getlasttasktimemillis() throws illegalstateexception {
        if (this.lasttaskinfo == null) {
            throw new illegalstateexception("no tasks run: can't get last task interval");
        } else {
            return this.lasttaskinfo.gettimemillis();
        }
    }

    public string getlasttaskname() throws illegalstateexception {
        if (this.lasttaskinfo == null) {
            throw new illegalstateexception("no tasks run: can't get last task name");
        } else {
            return this.lasttaskinfo.gettaskname();
        }
    }

    public stopwatch.taskinfo getlasttaskinfo() throws illegalstateexception {
        if (this.lasttaskinfo == null) {
            throw new illegalstateexception("no tasks run: can't get last task info");
        } else {
            return this.lasttaskinfo;
        }
    }

    public long gettotaltimemillis() {
        return this.totaltimemillis;
    }

    public double gettotaltimeseconds() {
        return (double) this.totaltimemillis / 1000.0d;
    }

    public int gettaskcount() {
        return this.taskcount;
    }

    public stopwatch.taskinfo[] gettaskinfo() {
        if (!this.keeptasklist) {
            throw new unsupportedoperationexception("task info is not being kept!");
        } else {
            return (stopwatch.taskinfo[]) this.tasklist.toarray(new stopwatch.taskinfo[this.tasklist.size()]);
        }
    }

    public string shortsummary() {
        return "stopwatch '" + this.id + "': running time (millis) = " + this.gettotaltimemillis();
    }

    public string prettyprint() {
        stringbuilder sb = new stringbuilder(this.shortsummary());
        sb.append('\n');
        if (!this.keeptasklist) {
            sb.append("no task info kept");
        } else {
            sb.append("-----------------------------------------\n");
            sb.append("ms     %     task name\n");
            sb.append("-----------------------------------------\n");
            numberformat nf = numberformat.getnumberinstance();
            nf.setminimumintegerdigits(5);
            nf.setgroupingused(false);
            numberformat pf = numberformat.getpercentinstance();
            pf.setminimumintegerdigits(3);
            pf.setgroupingused(false);
            stopwatch.taskinfo[] var7;
            int var6 = (var7 = this.gettaskinfo()).length;

            for (int var5 = 0; var5 < var6; ++var5) {
                stopwatch.taskinfo task = var7[var5];
                sb.append(nf.format(task.gettimemillis())).append("  ");
                sb.append(pf.format(task.gettimeseconds() / this.gettotaltimeseconds())).append("  ");
                sb.append(task.gettaskname()).append("\n");
            }
        }

        return sb.tostring();
    }

    @override
    public string tostring() {
        stringbuilder sb = new stringbuilder(this.shortsummary());
        if (this.keeptasklist) {
            stopwatch.taskinfo[] var5;
            int var4 = (var5 = this.gettaskinfo()).length;

            for (int var3 = 0; var3 < var4; ++var3) {
                stopwatch.taskinfo task = var5[var3];
                sb.append("; [").append(task.gettaskname()).append("] took ").append(task.gettimemillis());
                long percent = math.round(100.0d * task.gettimeseconds() / this.gettotaltimeseconds());
                sb.append(" = ").append(percent).append("%");
            }
        } else {
            sb.append("; no task info kept");
        }

        return sb.tostring();
    }

    public static final class taskinfo {
        private final string taskname;
        private final long timemillis;

        taskinfo(string taskname, long timemillis) {
            this.taskname = taskname;
            this.timemillis = timemillis;
        }

        public string gettaskname() {
            return this.taskname;
        }

        public long gettimemillis() {
            return this.timemillis;
        }

        public double gettimeseconds() {
            return (double) this.timemillis / 1000.0d;
        }
    }

}

到此这篇关于spring计时器stopwatch使用详解的文章就介绍到这了,更多相关spring计时器stopwatch内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Spring stopwatch