Simple Benchmark Aspect

Friday, July 16 2010 @ 10:08 AM UTC

Contributed by: Admin

You need to benchmark Java methods in a cumulative way ? Here a simple Aspect to do itů

The Aspect itself:


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 ;
	}
	
}
The annotation to mark methods to be benchmarked:

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()
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Benchmark {
	String		name()  ;
}
Example of annotated method:

@Benchmarg(name="mybenchmark1")
public void method1()
{
...
}
The cumul of benchmarks being done based on the name given in the annotation, you may sum time spend in several different methods unde the same key.

Example of out to output results:

 for(Map.Entry<String, Long> e : BenchmarkAspect.aspectOf().getBenchmarks().entrySet() ) {
 	System.out.println(e.getKey() + "=" + (float)((e.getValue() / 1000) / 1000) / 1000.0f + " secs") ;
 }

0 comments



http://www.macosxguru.net/article.php?story=2010071611082061