当前位置:网站首页>Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
2022-06-22 13:41:00 【Java technology stack】
background
You're still using System.currentTimeMillis... Statistics take time ?
For example, the following code :
/**
* @author: Stack leader
* @from: official account Java Technology stack
*/
@Test
public void jdkWasteTime() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(3000);
System.out.printf(" Time consuming :%dms.", System.currentTimeMillis() - start);
}System.currentTimeMillis... This method of time-consuming statistics is indeed the most used , Because it doesn't have to introduce other JAR package ,JDK You can get , But it has a few inconvenient places to use :
1) Initial time value needs to be defined , Use the current time for manual calculation ;
2) It is troublesome to count the time consumption of multiple tasks , If start Incorrect assignment may also cause logic problems ;
Is there a better alternative ? The answer is yes :StopWatch!
StopWatch
StopWatch It is a time-consuming tool class :

frequently-used StopWatch There are two types of tool classes :
- commons-lang3(Apache General toolkit provided )
- spring-core(Spring Core packages )
Although the names of the two tool classes are the same , But the usage is quite different , In this article, the stack leader will show you .
commons-lang3 Provided StopWatch
Introduce dependencies
commons-lang3 yes Apache Open source universal Toolkit , Additional introduction required Maven rely on :
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>A simple example
Create a StopWatch Examples are as follows 3 Methods :
1) Use new keyword
StopWatch sw = new StopWatch();2) Use create Factory method
StopWatch sw = StopWatch.create();3) Use createStarted Method
StopWatch sw = StopWatch.createStarted();This method will not only create an instance , It also starts the timing .
Let's take a simple example :
// Create a StopWatch Instance and start timing
StopWatch sw = StopWatch.createStarted();
// Sleep 1 second
Thread.sleep(1000);
// 1002ms
System.out.printf(" Time consuming :%dms.\n", sw.getTime()); More usage
Continue with the previous example .
Pause time :
// Pause time
sw.suspend();
Thread.sleep(1000);
// 1000ms
System.out.printf(" The pause took :%dms.\n", sw.getTime()); Because of the pause , So still 1000ms, Dormant after a pause 1000 ms It won't be counted .
Resume timing :
// Resume timing
sw.resume();
Thread.sleep(1000);
// 2001ms
System.out.printf(" Recovery time :%dms.\n", sw.getTime()); Because of the recovery , The result is 2001 ms, Dormant after recovery 1000 ms It was counted .
Stop timing :
Thread.sleep(1000);
// Stop timing
sw.stop();
Thread.sleep(1000);
// 3009ms
System.out.printf(" Total time :%dms.\n", sw.getTime()); Sleep before stopping timing 1000ms, So the result is 3009ms, You can no longer use pause after you stop timing 、 The function is restored .
Reset timing :
// Reset timing
sw.reset();
// Start timing
sw.start();
Thread.sleep(1000);
// 1000ms
System.out.printf(" Reset time :%dms.\n", sw.getTime()); Because the reset timer , So when you start counting again, it becomes 1000ms.
All the complete sample source code of this article has been uploaded :
welcome Star Study , Back Java Examples will be provided above !
Spring Provided StopWatch
Let's take a simple example :
// Create a StopWatch example
StopWatch sw = StopWatch(" official account Java Technology stack : Test time ");
// Start timing
sw.start(" Mission 1");
// Sleep 1 second
Thread.sleep(1000);
// Stop timing
sw.stop();
// 1002ms
System.out.printf(" Mission 1 Time consuming :%d%s.\n", sw.getLastTaskTimeMillis(), "ms");Spring The way to create an instance is new, Start timing , And getting the time manually start、stop.
Continue to add 2 A mission :
Thread.sleep(1000);
sw.start(" Mission 2");
Thread.sleep(1100);
sw.stop();
// 1100ms.
System.out.printf(" Mission 2 Time consuming :%d%s.\n", sw.getLastTaskTimeMillis(), "ms");
sw.start(" Mission 3");
Thread.sleep(1200);
sw.stop();
// 1203ms.
System.out.printf(" Mission 3 Time consuming :%d%s.\n", sw.getLastTaskTimeMillis(), "ms");
// 3.309373456s.
System.out.printf(" Number of tasks :%s, Total time :%ss.\n", sw.getTaskCount(), sw.getTotalTimeSeconds());Spring An important highlight is the support for formatting print results :
System.out.println(sw.prettyPrint());Look at the final output :

But there is one thing that is not friendly , The formatted results are displayed in nanoseconds , And it can't be modified ..
Realization principle
Let's have a look at commons-lang3 and Spring The core source code of :


In fact, they all make use of JDK Medium System System classes to implement , It's just a series of packages .
summary
commons-lang3 Toolkits and Spring In the framework StopWatch Can easily complete the timing and total time of multiple tasks , No more time-consuming manual calculations , Manually calculate if start Assignment errors may also cause errors .
Of course , The above two StopWatch The function of is far more than that introduced by the stack manager , What the stack leader introduced is enough , More can be studied in depth .
All the complete sample source code of this article has been uploaded :
welcome Star Study , Back Java Examples will be provided above !
Summarize the advantages and disadvantages of these two timing tool classes :
1)commons-lang3 Medium StopWatch The usage of is better than Spring The one in is simpler ;
2)commons-lang3 Medium StopWatch Functional ratio Spring Be more flexible in 、 More powerful , Support pause 、 recovery 、 Reset and other functions ;
3)Spring Provide the name of each subtask , And the function of printing results by format , Better for multi task statistics ;
in summary , Personal recommendation commons-lang3 In the kit , More flexible 、 More powerful , If you don't want to introduce additional packages , You can also consider Spring Medium , According to your own system requirements .
therefore , Don't use System.currentTimeMillis... The statistics took time , too low, Share and forward quickly , Standardize !
Okay , Today's sharing is here , Later, the stack leader will share more fun Java Technology and the latest technical information , Official account Java The first time the technology stack pushes , I will also mainstream Java The interview questions and reference answers have been sorted out , Reply key in background of official account " interview " Write the questions .
Copyright notice : The official account is No. "Java Technology stack " original , Reprint 、 Please indicate the source of this article , Plagiarism 、 If you wash your manuscript, you will complain about infringement , Consequence conceit , And reserves the right to pursue its legal liability .
Recent hot article recommends :
1.1,000+ Avenue Java Arrangement of interview questions and answers (2022 The latest version )
2. Explode !Java Xie Cheng is coming ...
3.Spring Boot 2.x course , It's too complete !
4. Don't write about the explosion on the screen , Try decorator mode , This is the elegant way !!
5.《Java Development Manual ( Song Mountain version )》 The latest release , Download it quickly !
I think it's good , Don't forget to like it + Forward !
边栏推荐
- epoch_ Num and predict_ Conversion of num
- Acwing week 52
- 240. Search a 2D Matrix II
- leetcode LCP 10. Binary tree task scheduling
- “不敢去怀疑代码,又不得不怀疑代码”记一次网络请求超时分析
- Performance of recommender algorithms on top-N recommendation tasks
- Rce & Code Execution Vulnerability
- Leetcode interval DP
- “不敢去懷疑代碼,又不得不懷疑代碼”記一次網絡請求超時分析
- [Nacos cloud native] the first step of reading the source code is to start Nacos locally
猜你喜欢

基于SSM的图书馆管理系统,高质量毕业论文范例(可直接使用),项目导入视频,附送源码和数据库脚本,论文撰写教程

hw在即,你还不会看危险报文?

leetcode LCP 10. Binary tree task scheduling

【Nacos云原生】阅读源码第一步,本地启动Nacos

Configuring cplex12.4 tutorial in VS2010

SSM based library management system, high-quality graduation thesis example (can be used directly), project import video, attached source code and database script, Thesis Writing Tutorial

Word skills summary

JSP based library management system, including source code, database script, video tutorial for project operation, and video tutorial for thesis writing

Stored procedures in MySQL

PHP deserialization & Magic method
随机推荐
Istio服务网格中的流量复制
Shell基础入门
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
342. Power of Four
257. Binary Tree Paths
基于JSP的图书馆管理系统,包含源码,数据库脚本,项目运行视频教程,毕设论文撰写视频教程
Temporary recommendation on graphs via long- and short term preference fusion
Leetcode math problems
Leetcode union search set
PHP deserialization & Magic method
Tips of setup in robotframework
Oracle cursor
openGauss内核分析之查询重写
338. Counting Bits
Interaction between awk language and Oracle database for nearly half a year
leetcode 834. Sum of distances in the tree
Alicloud disk performance analysis
Stored procedures in MySQL
Oracle's skills in dealing with inserting duplicate records
Windows下MySQL 8.0.29的详细安装教程,解决找不到VCRUNTIME140_1.dll、plugin caching_sha2_password could not be loaded