@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.
Very useful. thanks for sharing
ReplyDeleteMy pleasure :-)
ReplyDeleteNeat!
ReplyDeleteInstead of prefix / suffix, you could also use Groovy 1.8's annotation closure parameters: @Benchmark({ "execution time of method(): ${time} ns" }).
Thank you, Guillaume! Actually I was about to replace prefix / suffix to template: @Benchmark("%method: %time ns")
ReplyDeleteI'll also try the way you suggested :-)