Use StopWatch to print the program time-consuming 使用StopWatch打印程序耗時
### 背景
最近看到現在的項目裡,有的程序員很負責,對自己寫的代碼性能如何很上心,會有很多這樣的代碼:
```java
long start = new Date().getTime();
//業務邏輯
long end = new Date().getTime();
system.out.println("耗時:" + (end - start) + "毫秒");
```
其實可以用StopWatch,更優雅,更何況springboot啟動的時候,打印的耗時就是用StopWatch。
### 示例
##### springboot啟動源碼
```java
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
this.configureHeadlessProperty();
SpringApplicationRunListeners listeners = this.getRunListeners(args);
listeners.starting();
Collection exceptionReporters;
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
Banner printedBanner = this.printBanner(environment);
context = this.createApplicationContext();
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
this.refreshContext(context);
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}
try {
listeners.running(context);
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
```
##### 統計輸出總耗時
```java
public class SpringStopWatchExample {
public static void main (String[] args) throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start();
//long task simulation
Thread.sleep(1000);
sw.stop();
System.out.println(sw.getTotalTimeMillis());
}
}
```
##### 輸出最後一個任務的耗時
```java
public class SpringStopWatchExample2 {
public static void main (String[] args) throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start("A");//setting a task name
//long task simulation
Thread.sleep(1000);
sw.stop();
System.out.println(sw.getLastTaskTimeMillis());
}
}
```
##### 以優雅的格式打出所有任務的耗時以及佔比
```java
public class SpringStopWatchExample3 {
public static void main (String[] args) throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start("A");
Thread.sleep(500);
sw.stop();
sw.start("B");
Thread.sleep(300);
sw.stop();
sw.start("C");
Thread.sleep(200);
sw.stop();
System.out.println(sw.prettyPrint());
}
}
```
輸出:
```
StopWatch '': running time (millis) = 1031
-----------------------------------------
ms % Task name
-----------------------------------------
00514 050% A
00302 029% B
00215 021% C
```
### 不同的打印結果
- getTotalTimeSeconds() 獲取總耗時秒,同時也有獲取毫秒的方法
- prettyPrint() 優雅的格式打印結果,表格形式
- shortSummary() 返回簡短的總耗時描述
- getTaskCount() 返回統計時間任務的數量
- getLastTaskInfo().getTaskName() 返回最後一個任務TaskInfo對象的名稱
- https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/StopWatch.html
喜歡我的作品嗎?別忘了給予支持與讚賞,讓我知道在創作的路上有你陪伴,一起延續這份熱忱!