当前位置: 代码网 > it编程>编程语言>Java > Java中StopWatch的使用示例详解

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使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com