Contribute  :  Calendar  :  Advanced Search  :  Site Statistics  :  Directory  :  Files to download  :  Links for developers  :  Privacy policy  :  Web Resources  :  Polls  
    MacOSX Guru Site Information, tips and tricks, FAQ for Mac OS X developers    
 Welcome to MacOSX Guru Site
 Sunday, October 26 2014 @ 01:01 AM UTC

Simple Benchmark Aspect

   
Java DevelopmentYou 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({ElementType.METHOD})
@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") ;
 }
 

What's Related

Story Options

Simple Benchmark Aspect | 0 comments | Create New Account
The following comments are owned by whomever posted them. This site is not responsible for what they say.
 Copyright © 2014 MacOSX Guru Site
 All trademarks and copyrights on this page are owned by their respective owners.
Powered By Geeklog 
Created this page in 0.06 seconds