当前位置:网站首页>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-07-03 03:12:00 【Friendship years】
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 :
https://github.com/javastacks/javastack
welcome Star Study , Back Java Examples will be provided above ! in addition , The latest interview questions have been sorted out , You can Java Interview database Small program online brush questions .
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 .. Click on the official account ,Java dried food Timely delivery


Java Technology stack
Focus on sharing Java Technical dry cargo , Including multithreading 、JVM、Spring Boot、Spring Cloud、Intellij IDEA、Dubbo、Zookeeper、Redis、 Architecture design 、 Microservices 、 Message queue 、Git、 Interview questions 、 Programmer strategy 、 Latest news, etc .
514 Original content
official account
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 :
https://github.com/javastacks/javastack
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 .
边栏推荐
- 文件重命名
- el-tree搜索方法使用
- Sqlserver row to column pivot
- How to use asp Net MVC identity 2 change password authentication- How To Change Password Validation in ASP. Net MVC Identity 2?
- How to select the minimum and maximum values of columns in the data table- How to select min and max values of a column in a datatable?
- QT based tensorrt accelerated yolov5
- Opengauss database development and debugging tool guide
- Vs 2019 configure tensorrt to generate engine
- PAT乙级常用函数用法总结
- @Accessors注解作用指定前缀遵守驼峰命名
猜你喜欢

Nasvit: neural architecture search of efficient visual converter with gradient conflict perception hypernetwork training

I2C subsystem (III): I2C driver

Privatization lightweight continuous integration deployment scheme -- 01 environment configuration (Part 2)
![MySQL practice 45 lecture [transaction isolation]](/img/a5/5420651d6be51e892976f02be8c43c.png)
MySQL practice 45 lecture [transaction isolation]

MySql实战45讲【全局锁和表锁】
![MySQL practice 45 lecture [row lock]](/img/71/344daddee537a96f0d38241e6896e1.png)
MySQL practice 45 lecture [row lock]

Opengauss database development and debugging tool guide

Distributed transaction

Creation and destruction of function stack frame

用docker 連接mysql的過程
随机推荐
Change cell color in Excel using C - cell color changing in Excel using C
将时间戳转为指定格式的时间
用docker 連接mysql的過程
PHP constructor with parameters - PHP constructor with a parameter
el-tree搜索方法使用
从C到Capable-----利用指针作为函数参数求字符串是否为回文字符
Vs 2019 configuration du moteur de génération de tensorrt
How to return ordered keys after counter counts the quantity
C语言初阶-指针详解-庖丁解牛篇
[C language] MD5 encryption for account password
Introduction to cron expression
后管中编辑与预览获取表单的值写法
Cron表达式介绍
Update and return document in mongodb - update and return document in mongodb
JS finds all the parent nodes or child nodes under a node according to the tree structure
解决高并发下System.currentTimeMillis卡顿
[Fuhan 6630 encodes and stores videos, and uses RTSP server and timestamp synchronization to realize VLC viewing videos]
900W+ 数据,从 17s 到 300ms,如何操作
How to implement append in tensor
C # general interface call