Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure time spent in Groovy Class Methods

I am writing some kind of profiler for my Groovy-based application. For that I am interested in how much processing time is spent in various of class methods.

Now it would work to simply measure the nanoseconds spent in each of these methods, by taking the start and end times of a method call. However, that feels clunky, I don't want to take the time "outside" the methods (e.g. before and after the call). I rather want to measure time within the class itself, but also not "manually" by taking the start and end times, but rather "automatically", if possible.

So my question is: What would be the nicest and most Groovy way to measure the time spent in various methods of a class? Maybe via annotations?

like image 821
Matthias Avatar asked Sep 11 '25 13:09

Matthias


1 Answers

Groovy ships with BenchmarkInterceptor:

Interceptor that registers the timestamp of each method call before and after invocation. The timestamps are stored internally and can be retrieved through the with the

getCalls()

and

statistic()

API.

Example usage:

def proxy = ProxyMetaClass.getInstance(ArrayList.class)
proxy.interceptor = new BenchmarkInterceptor()
proxy.use {
    def list = (0..10000).collect{ it }
    4.times { list.size() }
    4000.times { list.set(it, it+1) }
}
proxy.interceptor.statistic()

Which produces the following output:

[[size, 4, 0], [set, 4000, 21]]
like image 56
cfrick Avatar answered Sep 15 '25 01:09

cfrick