用StopWatch優(yōu)雅替代currentTimeMillis計算程序執(zhí)行耗時
需求
有時需要記錄程序執(zhí)行時間,最簡單就是打印當(dāng)前時間與執(zhí)行完時間的差值,缺點是:
- 執(zhí)行大量測試的話就很麻煩
- 不直觀
- 如果想對執(zhí)行的時間做進(jìn)一步控制,則需要在程序中很多地方修改
于是 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)文章
Java實現(xiàn)int、long、Integer、Long之間的相互轉(zhuǎn)換
本文主要介紹了Java實現(xiàn)int、long、Integer、Long之間的相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08Spring Boot使用profile如何配置不同環(huán)境的配置文件
,springboot支持通過不同的profile來配置不同環(huán)境的配置,下面就大致介紹一下yml配置文件跟properties配置文件怎么使用profile配置不同環(huán)境的配置文件2018-01-01