001 package groovy.lang;
002
003 import java.util.*;
004
005 /**
006 * Interceptor that registers the timestamp of each method call
007 * before and after invocation.
008 */
009 public class BenchmarkInterceptor implements Interceptor {
010
011 protected Map calls = new HashMap(); // keys to list of invokation times and before and after
012
013
014 public Map getCalls() {
015 return calls;
016 }
017 public void reset() {
018 calls = new HashMap();
019 }
020
021 public Object beforeInvoke(Object object, String methodName, Object[] arguments) {
022 if (!calls.containsKey(methodName)) calls.put(methodName, new LinkedList());
023 ((List) calls.get(methodName)).add(new Long(System.currentTimeMillis()));
024
025 return null;
026 }
027
028 public Object afterInvoke(Object object, String methodName, Object[] arguments, Object result) {
029 ((List) calls.get(methodName)).add(new Long(System.currentTimeMillis()));
030 return result;
031 }
032
033 public boolean doInvoke() {
034 return true;
035 }
036
037 /**
038 * @return a list of lines, each item is [methodname, numberOfCalls, accumulatedTime]
039 */
040 public List statistic() {
041 List result = new LinkedList();
042 for (Iterator iter = calls.keySet().iterator(); iter.hasNext();) {
043 Object[] line = new Object[3];
044 result.add(line);
045 line[0] = (String) iter.next();
046 List times = (List) calls.get(line[0]);
047 line[1] = new Integer(times.size() / 2);
048 int accTime = 0;
049 for (Iterator it = times.iterator(); it.hasNext();) {
050 Long start = (Long) it.next();
051 Long end = (Long) it.next();
052 accTime += end.longValue() - start.longValue();
053 }
054 line[2] = new Long(accTime);
055 }
056 return result;
057 }
058 }