public aspect BenchmarkAspect issingleton() { private Map<String, Long> _cumulativeBenchmarks = new HashMap<String,Long>() ; public pointcut benchmarked(): call(@Benchmark * *(..)) ; Object around():benchmarked(){ MethodSignature ms = (MethodSignature)thisJoinPointStaticPart.getSignature() ; Method m = ms.getMethod() ; Benchmark benchAnn = m.getAnnotation(Benchmark.class) ; String benchKey = benchAnn.name() ; Long curBenchValue = _cumulativeBenchmarks.get(benchKey) ; if (curBenchValue == null) curBenchValue = new Long(0L) ; final long start = System.nanoTime() ; Object result = proceed() ; final long end = System.nanoTime() ; curBenchValue += (end - start) ; _cumulativeBenchmarks.put(benchKey, curBenchValue) ; return result ; } public void resetBenchmarks() { _cumulativeBenchmarks = new HashMap<String,Long>() ; } public Map<String, Long> getBenchmarks() { return _cumulativeBenchmarks ; } }
import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Benchmark { String name() ; }
@Benchmarg(name="mybenchmark1") public void method1() { ... }
for(Map.Entry<String, Long> e : BenchmarkAspect.aspectOf().getBenchmarks().entrySet() ) { System.out.println(e.getKey() + "=" + (float)((e.getValue() / 1000) / 1000) / 1000.0f + " secs") ; }