欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

Java中StopWatch的使用示例详解

2025年04月02日 Java
stopwatch 是org.springframework.util 包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比。在未使用这个工具类之前,如果我们需要统计某段代码的耗时,我

stopwatch 是org.springframework.util 包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比。

在未使用这个工具类之前,如果我们需要统计某段代码的耗时,我们会这样写:

public static void main(string[] args) throws interruptedexception {
    test0();
}
public static void test0() throws interruptedexception {
    long start = system.currenttimemills();
    // do something
    thread.sleep(100);
    long end = system.currenttimemills();
    long start2 = system.currenttimemills();
    // do somethind
    long end2 = system.currenttimemills();
    system.out.println("某某1执行耗时:" + (end -start));
    system.out.println("某某2执行耗时:" + (end2 -start2));
}

如果改用stopwatch 实现的一个示例

public class stopwatchdemo {
    public static void main(string[] args) throws interruptedexception {
         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 someting
       thread.sleep(200);
       sw.stop();
       system.out.println("sw.prettyprint()-------");
       system.out.println(sw.prettyprint());
    }
}

运行结果如下:

sw.prettyprint()------
stopwatch 'test': running time (millis) = 310
-----------------------------------------
ms     %     task name
-----------------------------------------
00110  035%  task1
00200  065%  task2

通过start 与stop 方法分别记录开始时间与结束时间,其中在记录结束时间的时候,会维护一个链表类型的tasklist 属性,从而时该类可记录多个任务,最后的输出页仅仅是对之前的记录信息做了一个统一的归纳输出。

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

从代码上可以看出, 其原理为使用linklist 来承接历史任务,使用自身属性来承接当前的状态,调用start 的时候初始化自身状态,使用stop 的时候来结束当前的状态然后加入到linklist中

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