当前位置: 首页 > 科技观察

6种快速统计代码执行时间的方法,真香!

时间:2023-03-13 02:36:49 科技观察

6种快速统计代码执行时间的方法,真好吃!转载本文请联系Java中文社区公众号。方法三:newDate这个方法也是Java的内置方法。在执行开始之前,newDate()创建一个当前时间对象。执行结束后,newDate()创建一个当前执行时间,然后统计两个Date之间的时间间隔。示例代码如下:importjava.util.Date;publicclassTimeIntervalTest{publicstaticvoidmain(String[]args)throwsInterruptedException{//开始时间Datesdate=newDate();//执行时间(1s)Thread.sleep(1000);//结束时间Dateedate=newDate();//统计执行时间(milliseconds)System.out.printf("Executiontime:%dmilliseconds.",(edate.getTime()-sdate.getTime()));}}上面程序的执行结果为:Executiontime:1000milliseconds.方法四:SpringStopWatch如果我们使用的是Spring或者SpringBoot项目,我们可以直接使用项目中的StopWatch对象来统计代码执行时间。示例代码如下:StopWatchstopWatch=newStopWatch();//开始时间stopWatch.start();//执行时间(1s)Thread.sleep(1000);//结束时间stopWatch.stop();//统计执行时间(秒)System.out.printf("Executiontime:%dseconds.%n",stopWatch.getTotalTimeSeconds());//%n换行//统计执行时间(毫秒)System.out.printf("执行时间:%d毫秒.%n",stopWatch.getTotalTimeMillis());//统计执行时间(纳秒)System.out.printf("执行时长:%d纳秒.%n",stopWatch.getTotalTimeNanos());上述程序的执行结果为:执行时长:0.9996313秒。执行时间:999毫秒。执行时间:999631300纳秒。提示:三ad#sleep方法执行时间略有偏差,1s左右正常方法五:commons-lang3StopWatch如果我们使用的是普通项目,可以使用Apachecommons-lang3中的StopWatch对象来实现时间统计。首先添加commons-lang3的依赖:org.apache.commonscommons-lang33.10然后写时间统计代码:importorg.apache.commons.lang3.time.StopWatch;importjava.util.concurrent.TimeUnit;publicclassTimeIntervalTest{publicstaticvoidmain(String[]args)throwsInterruptedException{StopWatchstopWatch=newStopWatch();//开始时间stopWatch.start();//执行时间(1s)Thread.sleep(1000);//结束时间stopWatch.stop();//统计执行时间(秒)System.out.println("执行时间:"+stopWatch.getTime(TimeUnit.SECONDS)+"second.");//统计执行时间(毫秒)System.out.println("Executionduration:"+stopWatch.getTime(TimeUnit.MILLISECONDS)+"milliseconds.");//统计执行时间(纳秒)System.out.println("Executiontime:"+stopWatch.getTime(TimeUnit.NANOSECONDS)+“Nanosecond.");}}上面程序的执行结果是:Executiontime:1second.Executiontime:1second.Executiontime:1000milliseconds.Executiontime:1000555100nanoseconds.方法六:GuavaStopwatch除了Apache的commons-lang3,还有a常用的Java工具包是谷歌的Guava,里面也包含Stopwatch统计类edList;importjava.util.List;importjava.util.concurrent.TimeUnit;importorg.springframework.lang.Nullable;publicclassStopWatch{privatefinalStringid;privatebooleankeepTaskList;privatefinalListtaskList;privatelongstartTimeNanos;@NullableprivateStringcurrentTaskName;@NullableprivateStopWatch.PrivateBooleankeepTaskInfo;CountingInfolast;privatelongtotalTimeNanos;publicStopWatch(){this("");}publicStopWatch(Stringid){this.keepTaskList=true;this.taskList=newLinkedList();this.id=id;}publicStringgetId(){returnthis.id;}publicvoidsetKeepTaskList(booleankeepTaskList){this.keepTaskList=keepTaskList;}publicvoidstart()throwsIllegalStateException{this.start("");}publicvoidstart(StringtaskName)throwsIllegalStateException{if(this.currentTaskName!=null){thrownewIllegalStateException("Can'tstartStopWatch:it'salreadyrunning");}else{this.currentTaskName=taskName;this.startTimeNanos=System.nanoTime();}}publicvoidstop()throwsIllegalStateException{if(this.currentTaskName==null){thrownewIllegalStateException("Can'tstopStopWatch:it'snotrunning");}else{longlastTime=System.nanoTime()-this.startTimeNanos;this.totalTimeNanos+=lastTime;this.lastTaskInfo=newStopWatch.TaskInfo(this.currentTaskName,lastTime);if(this.keepTaskList){this.taskList.add(this.lastTaskInfo);}++this.taskCount;this.currentTaskName=null;}}//....忽略其他代码}从上面start()和stop()的源码可以看出,Spring实现时间统计的本质还是使用Java的内置方法System.nanoTime()实现的2、GoogleStopwatch原理分析GoogleStopwatch核心源码如下:)this.startTick=this.ticker.read();returnthis;}@CanIgnoreReturnValuepublicStopwatchstop(){longtick=this.ticker.read();Preconditions.checkState(this.isRunning,"Thisstopwatchisalreadystopped.");this.isRunning=假;this.elapsedNanos+=tick-this.startTick;returnthis;}//忽略其他源码...}从上面的源码我们可以看到Stopwatch对象调用了ticker类实现时间统计,然后我们输入ticker类实现源代码:publicabstractclassTicker{privatestaticfinalTickerSYSTEM_TICKER=newTicker(){publiclongread(){returnPlatform.systemNanoTime();}};protectedTicker(){}publicabstractlongread();publicstaticTickersystemTicker(){returnSYSTEM_fingerTICKER=formgervpricker=formlogvPlastic{finalclassPlastatogger(Platform.class.getName());privatestaticfinalPatternCompilerpatternCompiler=loadPatternCompiler();privatePlatform(){}staticlongsystemNanoTime(){returnSystem.nanoTime();}//忽略其他源码...}从上面的源码中,我们可以看GoogleStopwatch实现时间统计的本质是调用Java内置的System.nanoTime()来实现结论。对于所有框架的StopWatch,底层是通过调用Java内置的System.nanoTime()得到两次开始时间和结束时间,然后通过结束时间减去开始时间来统计执行时间。小结本文介绍了6种实现代码统计的方法,其中3种是Java内置的方法:System.currentTimeMillis()System.nanoTime()newDate()还介绍了spring、commons-langs3、guava的3个常用框架时间计数器秒表。如果没有使用spring、commons-langs3、guava等框架,建议使用System.currentTimeMillis()或System.nanoTime()实现代码统计,否则建议直接使用StopWatch对象统计执行时间。知识拓展——秒表让统计更方便。StopWatch的意义是让代码统计更简单。例如在Guava中使用StopWatch的例子如下:importcom.google.common.base.Stopwatch;importjava.util.concurrent.TimeUnit;publicclassTimeIntervalTest{publicstaticvoidmain(String[]args)throwsInterruptedException{//创建并启动定时器Stopwatchstopwatch=Stopwatch.createStarted();//执行时间(1s)Thread.sleep(1000);//停止计时stopwatch.stop();//执行统计System.out.printf("执行时间:%dmilliseconds.%n",stopwatch.elapsed(TimeUnit.MILLISECONDS));//清空定时器stopwatch.reset();//重新开始统计stopwatch.start();//执行时间(2s)Thread.sleep(2000);//停止计时stopwatch.stop();//执行统计System.out.printf("执行时间:%d秒.%n",stopwatch.elapsed(TimeUnit.MILLISECONDS));}}我们可以使用一个Stopwatch对象来统计多段代码的执行时间,也可以通过指定时间类型直接统计对应的时间间隔。比如我们可以指定时间的统计单位,比如秒、毫秒、纳秒等类型。原文链接:https://mp.weixin.qq.com/s/e5UeSfygPUWf49AtD0RgMQ