首页 > 作文

Java计时新姿势StopWatch的使用方法详解

更新时间:2023-04-04 13:05:47 阅读: 评论:0

一、背景

有时我们在做开发的时候需要记录每个任务执行时间,或者记录一段代码执行时间,最简单的方法就是打印当前时间与执行完时间的差值,一般我们检测某段代码执行的时间,都是以如下方式来进行的:

public static void main(string[] args) {  long starttime = system.currenttimemillis();  // 你的业务代码  long endtime = system.currenttimemillis();  long elapdtime = (endtime - starttime) / 1000;  system.out.println("该段总共耗时:" + elapdtime + "s");}

事实上该方法通过获取执行完成时间与执行开始时间的差值得到程序的执行时间,简单直接有效,但想必写多了也是比较烦人的,尤其是碰到不可描述的代码时,会更加的让人忍不住多写几个bug聊表敬意,而且如果想对执行的时间做进一步控制,则需要在程序中很多地方修改。此时会想是否有一个工具类,提供了这些方法,刚好可以满足这种场景?我英语ab级考试时间们可以利用已有的工具类中的秒表,常见的秒表工具类有 org.springframework.util.stopwatchorg.apache.commons.lang.time.stopwatch以及谷歌提供的guava中的秒表(这个我没怎么用过)。这里重点讲下基于spring、apache的使用

二、spring 用法

2.1 初遇

stopwatch 是位于 org.springframework.util 包下的一个工具类,通过它可方便的对程序部分代码进行计时(ms级别),适用于同步单线程代码块。简单总结一句,spring提供的计时器stopwatch对于秒、毫秒为单位方便计时的程序,尤其是单线程、顺序执行程序的时间特性的统计输出支持比较好。也就是说假如我们手里面有几个在顺序上前后执行的几个任务,而且我们比较关心几个任务分别执行的时间占用状况,希望能够形成一个不太复杂的日志输出,stopwatch提供了这样的功能。而且spring的stopwatch基本上也就是仅仅为了这样的功能而实现。

想要使用它,首先你需要在你的 maven 中引入 spring 核心包,当然 spring mvc 和 spring boot 都已经自动引入了该包:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core --><dependency>    <groupid>org.springframework</groupid>    <artifactid>spring-core</artifactid>    <version>${spring.version}</version></dependency>

对一切事物的认知,都是从使用开始,那就先来看看它的用法,会如下所示:

public static void main(string[] args) throws interruptedexception {    stopwatch stopwatch = new stopwatch();    // 任务一模拟休眠3秒钟    stopwatch.start("taskonename");    thread.sleep(1000 * 3);    system.out.println("当前任务名称:" + stopwatch.currenttaskname());    stopwatch.stop();    // 任务一模拟休眠10秒钟    stopwatch.start("tasktwoname");    thread.sleep(1000 * 10);    system.out.println("当前任务名称:" + stopwatch.currenttask大班春季育儿知识name());    stopwatc河北专接本报名入口官网h.stop();    // 任务一模拟休眠10秒钟    stopwatch.start("taskthreename");    thread.sleep(1000 * 10);    system.out.println("当前任务名称:" + stopwatch.currenttaskname());    stopwatch.stop();    // 打印出耗时    system.out.println(stopwatch.prettyprint());    system.out.println(stopwatch.shortsummary());    // stop后它的值为null    system.out.println(stopwatch.currenttaskname());         // 最后一个任务的相关信息    system.out.println(stopwatch.getlasttaskname());    system.out.println(stopwatch.getlasttaskinfo());        // 任务总的耗时  如果你想获取到每个任务详情(包括它的任务名、耗时等等)可使用    system.out.println("所有任务总耗时:" + sw.gettotaltimemillis());    system.out.println("任务总数:" + sw.gettaskcount());    system.out.println("所有任务详情:" + sw.gettaskinfo());}

如图所示,stopwatch 不仅正确记录了上个任务的执行时间,并且在最后还可以给出精确的任务执行时间(纳秒级别)和耗时占比,这或许就会比我们自己输出要优雅那么一些。

2.2 源码

老规矩,由浅入深。看完用法,我们来看看源码。先看下组成 stopwatch 的属性

public class stopwatch {    /** * 本实例的唯一 id,用于在日志或控制台输出时区分的。 */    private final string id;    /** * 是否保持一个 tasklist 链表 * 每次停止计时时,会将当前任务放入这个链表,用以记录任务链路和计时分析 */private boolean keeptasklist = true;   /** * 任务链表 * 用来存储每个task的信息, taskinfo由taskname 和 totoaltime组成 */    private final list<stopwatch.taskinfo> tasklist;    /** * 当前任务的开始时间 */    private long starttimemillis;    /** *  */    private boolean running;    /** * 当前任务名称 */    private string currenttaskname;    /** * 最后一个任务的信息 */    private stopwatch.taskinfo lasttaskinfo;    /** * 任务总数 */    private int taskcou星空歌词nt;    /** * 程序执行时间 */    private long totaltimemillis;    ...}

接下来,我们看一下stopwatch类的构造器和一些关键方法

方法说明new stopwatch()构建一个新的秒表,不开始任何任务。new stopwatch(string id)创建一个指定了id的stopwatchstring getid()一根稻草返回此秒表的idvoid start(string taskname)不传入参数,开始一个无名称的任务的计时。 传入string类型的参数来开始指定任务名的任务计时void stop()停止当前任务的计时boolean isrunning()是否正在计时某任务string currenttaskname()当前正在运行的任务的名称(如果有)long gettotaltimemillis()所有任务的总体执行时间(毫秒单位)double gettotaltimeconds()所有任务的总时间(以秒为单位)string getlasttaskname()上一个任务的名称long getlasttasktimemillis()上一个任务的耗时(毫秒单位)int gettaskcount()定时任务的数量string shortsummary()总运行时间的简短描述string prettyprint()优美地打印所有任务的详细耗时情况

2.3 注意事项

stopwatch对象不是设计为线程安全的,并且不使用同步。一个stopwatch实例一次只能开启一个task,不能同时start多个task在该task还没stop之前不能start一个新的task,必须在该task stop之后才能开启新的task若要一次开启多个,需要new不同的stopwatch实例

三、apache 用法

stopwath是 apache commons lang3 包下的一个任务执行时间监视器,与我们平时常用的秒表的行为比较类似,我们先看一下其中的一些重要方法:

方法说明new stopwatch()构建一个新的秒表,不开始任何任务。static stopwatch createstarted()void start()开始计时void stop()停止当前任务的计时void ret()重置计时void split()设置split点void unsplit()void suspend()暂停计时, 直到调用resume()后才恢复计时void resume()恢复计时long gettime()统计从start到现在的计时long gettime(final timeunit timeunit)long getnanotime()long getsplittime()获取从start 到 最后一次split的时间long getsplitnanotime()long getstarttime()boolean isstarted()boolean issuspended()boolean isstopped()
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --><dependency>    <groupid>org.apache.commons</groupid>    <artifactid>commons-lang3</artifactid>    <version>3.6</version></dependency>

apache提供的这个任务执行监视器功能丰富强大,灵活性强,如下经典实用案例:

public static void main(string[] args) throws interruptedexception {    //创建后立即start,常用    stopwatch watch = stopwatch.createstarted();    // stopwatch watch = new stopwatch();    // watch.start();    thread.sleep(1000);    system.out.println(watch.gettime());    system.out.println("统计从开始到现在运行时间:" + watch.gettime() + "ms");    thread.sleep(1000);    watch.split();    system.out.println("从start到此刻为止的时间:" + watch.gettime());    system.out.println("从开始到第一个切入点运行时间:" + watch.getsplittime());    thread.sleep(1000);    watch.split();    system.out.println("从开始到第二个切入点运行时间:" + watch.getsplittime());    // 复位后, 重新计时    watch.ret();    watch.start();    thread.sleep(1000);    system.out.println("重新开始后到当前运行时间是:" + watch.gettime());    // 暂停 与 恢复    watch.suspend();    system.out.println("暂停2秒钟");    thread.sleep(2000);    // 上面suspend,这里要想重新统计,需要恢复一下    watch.resume();    system.out.println("恢复后执行的时间是:" + watch.gettime());    thread.sleep(1000);    watch.stop();    system.out.println("花费的时间》》" + watch.gettime() + "ms");    // 直接转成s    system.out.println("花费的时间》》" + watch.gettime(timeunit.conds) + "s");}

四、java 中使用stopwatch来计算时间差

以前在进行时间耗时时我们通常的做法是先给出计算前后两个的时间值,然后通过详见来计算耗时时长。

eg:

long start = system.currenttimemillis();      ......业务处理system.out.println("耗时:" + (system.currenttimemillis() - start) + "ms");

我们可以使用已有的工具类中的秒表来替代上述的使用方式,现有的秒表工具类有org.springframework.util.stopwatch、org.apache.commons.lang.time.stopwatch,这里以spring的stopwatch类为例:

public static void main(string[] args) throws interruptedexception{        stopwatch stopwatch = new stopwatch("任务耗时秒表工具");        stopwatch.start("task1");        thread.sleep(1000);        stopwatch.stop();        system.out.println(stopwatch.gettotaltimemillis());        stopwatch.start("task2");        thread.sleep(3000);        stopwatch.stop();        //所有任务耗时时间        system.out.println(stopwatch.gettotaltimemillis());        system.out.println(stopwatch.prettyprint());        stopwatch stopwatch2 = new stopwatch("任务耗时秒表工具2");        stopwatch2.start("task3");        thread.sleep(3000);        stopwatch2.stop();        //所有任务耗时时间        system.out.println(stopwatch2.gettotaltimemillis());        system.out.println(stopwatch2.prettyprint());    }

五、最后

很多时候,写代码也是一种艺术,而借助这种实用工具我就觉得艺术感更强些。希望我们能有追求更加美好事物的心,这点对于接纳新知识特别重要。此处推荐这个监视器来代替之前的的使用,能让小伙伴们更加灵活的分析你的代码~

到此这篇关于java计时新姿势stopwatch使用的文章就介绍到这了,更多相关java计时stopwatch内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-04 13:05:33,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/66eb7bd50a7988abdef02e708ba0bc01.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:Java计时新姿势StopWatch的使用方法详解.doc

本文 PDF 下载地址:Java计时新姿势StopWatch的使用方法详解.pdf

标签:时间   秒表   执行时间   代码
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图