用StopWatch優(yōu)雅替代currentTimeMillis計算程序執(zhí)行耗時
需求
有時需要記錄程序執(zhí)行時間,最簡單就是打印當前時間與執(zhí)行完時間的差值,缺點是:
- 執(zhí)行大量測試的話就很麻煩
- 不直觀
- 如果想對執(zhí)行的時間做進一步控制,則需要在程序中很多地方修改
于是 Spring提供了一個StopWatch類可以做類似任務(wù)執(zhí)行時間控制,即封裝了一個對開始時間,結(jié)束時間記錄工具
案例
統(tǒng)計輸出總耗時
import org.springframework.util.StopWatch;
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());
}
}
輸出最后一個任務(wù)的耗時
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());
}
}
以優(yōu)雅的格式打出所有任務(wù)的耗時以及占比
import org.springframework.util.StopWatch;
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());
}
}
序列服務(wù)輸出耗時信息
@Override
public long nextSeq(String name) {
StopWatch watch = new StopWatch();
watch.start("單序列獲取總消耗");
long sequence = generator.generateId(name);
watch.stop();
logger.info(watch.prettyPrint());
return sequence;
}
getTotalTimeSeconds() 獲取總耗時秒,同時也有獲取毫秒的方法
prettyPrint() 優(yōu)雅的格式打印結(jié)果,表格形式
shortSummary() 返回簡短的總耗時描述
getTaskCount() 返回統(tǒng)計時間任務(wù)的數(shù)量
getLastTaskInfo().getTaskName() 返回最后一個任務(wù)TaskInfo對象的名稱
到此這篇關(guān)于用StopWatch優(yōu)雅替代currentTimeMillis計算程序執(zhí)行耗時的文章就介紹到這了,更多相關(guān)Java StopWatch內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Maven添加Tomcat插件實現(xiàn)熱部署代碼實例
這篇文章主要介紹了Maven添加Tomcat插件實現(xiàn)熱部署代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04
IDEA創(chuàng)建SpringBoot的maven項目的方法步驟
這篇文章主要介紹了IDEA創(chuàng)建SpringBoot的maven項目的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Spring Junit測試找不到SpringJUnit4ClassRunner.class的解決
這篇文章主要介紹了Spring Junit測試找不到SpringJUnit4ClassRunner.class的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04

