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