I'm trying to come-up with a utility method to log the time duration taken by code blocks in my java code. Please find below the utility code to log duration and the main code using the utility method,
Utility code:
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());
}
Main code:
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");
Sample Output: Time taken to complete Parsing and Splitting Persons list - PT0.012S
This seems to be working fine but i want to make sure this implementation does not have any adverse unwanted hidden impacts to my code execution. Could you please let me know the design flaws in this implementation? Or please let me know if there are any alternate implementation.