當前位置: 妍妍網 > 碼農

今日程式碼 PK | 優雅統計耗時

2024-03-18碼農

在開發中,介面的效能(特別是耗時)最佳化是必不可少的,

而最佳化的前提是搞清楚是哪個步驟比較耗時。

統計耗時的方式有很多,比如使用 System 時間戳,

範例程式碼如下:

/**
 * @author pine
 */

public classMain {
publicstaticvoidmain(String[] args) throws Exception{
// 任務1
longstart1 = System.currentTimeMillis();
Thread.sleep(1000);
longend1 = System.currentTimeMillis();
// 任務2
longstart2 = System.currentTimeMillis();
Thread.sleep(2000);
longend2 = System.currentTimeMillis();
// 打印出耗時
System.out.println(end1 - start1);
System.out.println(end2 - start2);
}
}


當然也有現成的工具實作,比如 Hutool StopWatch

不僅操作方便,打印的結果也更加易讀、美觀。

範例程式碼如下:

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.lang.Console;
/**
 * @author pine
 */

public classMain {
publicstaticvoidmain(String[] args) throws Exception{
StopWatchstopWatch = newStopWatch("任務名稱");
// 任務1
stopWatch.start("任務一");
Thread.sleep(1000);
stopWatch.stop();
// 任務2
stopWatch.start("任務二");
Thread.sleep(2000);
stopWatch.stop();
// 打印出耗時
// StopWatch '任務名稱': running time = 3010773584 ns
// ---------------------------------------------
// ns % Task name
// ---------------------------------------------
// 1005736375 33% 任務一
// 2005037209 67% 任務二
Console.log(stopWatch.prettyPrint());
}
}



大家更喜歡哪種呢?歡迎投票並在評論區留下自己的看法。

完整程式碼片段來源於程式碼小抄,歡迎點選進入小程式閱讀!

線上存取:https://www.codecopy.cn/post/61ot1g

更多優質程式碼歡迎進入小程式檢視!

往期推薦