About Me

My photo
Author of Groovy modules: GBench, GProf, Co-author of a Java book パーフェクトJava, Game Developer at GREE

Saturday, May 28, 2011

I released @Benchmark annotation for Groovy!

@Benchmark annotation allows to measure execution time of methods without adding code. The following example is the standard use of @Benchmark:
----
@Benchmark
def method() {
    // an operation takes 1 ms
}


method()
----
In this case, "1000000" will be printed out in the standard output. @Benchmark express the time in nanoseconds.


There are two options to customize the output format:
----
@Benchmark(prefix = 'execution time of method(): ', suffix = ' ns')
def method() {
    // an operation takes 1 ms
}


method()
----
Then the output will be "execution time of method(): 1000000 ns".


@Benchmark uses this.println(value) for printing out. So you can redirect the outputs by setting an appropriate writer for the purpose to the "out" property:
----
def results = new StringBuffer()
this.setProperty("out", new StringBufferWriter(results))


// method calls


this.setProperty("out", null)


results.toString().eachLine { result ->
    println "${result.asType(int.class) / 1000000} ms"
}
----


You can download it from here.

4 comments:

  1. Very useful. thanks for sharing

    ReplyDelete
  2. Neat!
    Instead of prefix / suffix, you could also use Groovy 1.8's annotation closure parameters: @Benchmark({ "execution time of method(): ${time} ns" }).

    ReplyDelete
  3. Thank you, Guillaume! Actually I was about to replace prefix / suffix to template: @Benchmark("%method: %time ns")
    I'll also try the way you suggested :-)

    ReplyDelete