DRY benchmarking….

May 13th, 2008

Every time we try to write a benchmark for particular functionality, we habitually specify a load (max iterations), write a for-loop, set timers before and after the loop, and call the method of interest inside this loop. This typically involves copying & pasting from another benchmark and adapting the current benchmark to your needs. Why don’t we try, instead of copy & paste, to define an idiom that we could reuse for writin benchmarks? Something like this


public class Benchmark {
    private final int iters;
    public Benchmark(int iters){
        this.iters = iters;
    }

    public <T>long given(
    final Callable<? extends T> op
    ) throws Exception
    {
    	// warm things up
        for(int idx = 0; idx < 10000; idx++){}

        long time = System.nanoTime();
        for(int idx = 0; idx < iters; idx++){
            op.call();
        }
        time = System.nanoTime() - time;
        return TimeUnit.NANOSECONDS.toMillis(time);
    }
}

How can use this? This is simple….


    public static void main(
    String[] args
    ) throws Exception
    {
      System.out.println(new Benchmark(100000).given(
      	new Callable<Void>(){
            public Void call() throws Exception {
                System.out.println();
                return null;
            }
      }));
    }

Using this idiom will make the benchmarking of method calls easier…So please start using it :)

patterns, programming | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
  5. Spam Protection by WP-SpamFree

You can keep track of new comments to this post with the comments feed.

 

May 2008
M T W T F S S
« Apr   Jun »
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

Archives

Tags