记录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
这似乎工作正常,但我想确保这个实现不会对我的代码执行产生任何不必要的负面影响。你能告诉我这个实现中的设计缺陷吗?或者请告诉我是否有其他实施方案
# 1 楼答案
听起来你想要一个秒表,guava有:
除非你想测试你的代码。微观基准就是这样。在这种情况下
JMH
实际上是实现这一点的工具。阅读更多here# 2 楼答案
看看JMH这样的微基准框架:JMH是一种Java工具,用于构建、运行和分析用Java和其他针对JVM的语言编写的nano/micro/milli/macro基准