Skip to content

Instantly share code, notes, and snippets.

@eddiewebb
Created March 19, 2018 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddiewebb/4848c39edcc7cbbf89c8437e29a81726 to your computer and use it in GitHub Desktop.
Save eddiewebb/4848c39edcc7cbbf89c8437e29a81726 to your computer and use it in GitHub Desktop.
Timing Java method calls.
// This allows you to call methods wrapped in a timer for profilling.
// I used in a scenario where my abstract class delegated back to concrete implementations, and wanted to be aware of duration.
// Because timer runs in a lambda, it doesn't require any special treatment to see/manipulate current context/scope.
public abstract class AbstractClass{
public final loadDependencies(Map<String, Object> map){
//here we call some methods, they could be anywhere.
ChainResultsSummary results = timing("getChainResultsSummary",() -> getChainResultsSummary(map));
ImmutableChain chain = timing("getImmutableChain",() -> getImmutableChain(map));
List<DeploymentProject> relatedDeployProjects = timing("relatedDeploymentProjects",() -> getRelatedDeploymentProjects(map));
List<DeploymentProjectStatusForResultSummary> relatedDeployResults = timing("relatedDeployResults",() -> getRelatedDeploymentResults(map));
}
public <R> R timing(String name,Supplier<R> operation) {
long start = System.nanoTime();
R result = operation.get();
if(log.isTraceEnabled()){
log.trace( String.format("Execution of %s took %dms\n",name, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment