我試圖用實用方法來記錄代碼塊在我的java代碼中所用的持續時間。請看以下程序代碼,登錄時間和使用工具方法的主要代碼,Java - 記錄持續時間的實用方法
實用代碼:
public static void logDuration(Runnable blockToExec
, String blockCode) {
Instant start = Instant.now();
blockToExec.run();
Duration duration = Duration.between(start, Instant.now());
/*
SAMPLE OUPUT of below print stmt (from JAVA API doc)
"20.345 seconds" -- "PT20.345S
"15 minutes" (15 * 60 seconds) -- "PT15M"
"10 hours" (10 * 3600 seconds) -- "PT10H"
"2 days" (2 * 86400 seconds) -- "PT48H"
*/
System.out.println("Time taken to complete <" + blockCode + "> - " + duration.toString());
}
主要代碼:
Utils.logDuration(() -> {
List<PersonInfo> personInfos = persons.stream()
.flatMap(person -> person.getCurrAndPrevAddrs().stream()
.map(addr -> {
PersonInfo personInfo = new PersonInfo();
personInfo.setName(person.getName());
personInfo.setAge(person.getAge());
personInfo.setAddrs(addr);
return personInfo;
}
)).collect(Collectors.toList());
}, "Parsing and Splitting Persons list");
樣本輸出: 完成分析和分割人員列表所需的時間 - PT0.012S
這似乎工作正常,但我想確保這個實現沒有任何不利的不想要的隱藏影響到我的代碼執行。你能讓我知道這個實現中的設計缺陷嗎?或者請讓我知道是否有任何替代實施。
[CodeReview](http://codereview.stackexchange.com/)將是這種問題的最佳StackExchange :) – Aaron
您應該使用System.nanoTime。當然,創建Runnable實例,最重要的是打印到控制檯,會讓你的代碼變慢。如果您在代碼中計算熱點,這可能很重要。你的設計中的另一個問題是,你不能計算任何需要返回某個東西或拋出檢查異常的東西。 –