01: package groovy.lang;
02:
03: import java.util.*;
04:
05: /**
06: * Interceptor that registers the timestamp of each method call
07: * before and after invocation.
08: */
09: public class BenchmarkInterceptor implements Interceptor {
10:
11: protected Map calls = new HashMap(); // keys to list of invokation times and before and after
12:
13: public Map getCalls() {
14: return calls;
15: }
16:
17: public void reset() {
18: calls = new HashMap();
19: }
20:
21: public Object beforeInvoke(Object object, String methodName,
22: Object[] arguments) {
23: if (!calls.containsKey(methodName))
24: calls.put(methodName, new LinkedList());
25: ((List) calls.get(methodName)).add(new Long(System
26: .currentTimeMillis()));
27:
28: return null;
29: }
30:
31: public Object afterInvoke(Object object, String methodName,
32: Object[] arguments, Object result) {
33: ((List) calls.get(methodName)).add(new Long(System
34: .currentTimeMillis()));
35: return result;
36: }
37:
38: public boolean doInvoke() {
39: return true;
40: }
41:
42: /**
43: * @return a list of lines, each item is [methodname, numberOfCalls, accumulatedTime]
44: */
45: public List statistic() {
46: List result = new LinkedList();
47: for (Iterator iter = calls.keySet().iterator(); iter.hasNext();) {
48: Object[] line = new Object[3];
49: result.add(line);
50: line[0] = (String) iter.next();
51: List times = (List) calls.get(line[0]);
52: line[1] = new Integer(times.size() / 2);
53: int accTime = 0;
54: for (Iterator it = times.iterator(); it.hasNext();) {
55: Long start = (Long) it.next();
56: Long end = (Long) it.next();
57: accTime += end.longValue() - start.longValue();
58: }
59: line[2] = new Long(accTime);
60: }
61: return result;
62: }
63: }
|