Skip to content

Instantly share code, notes, and snippets.

@superbob
Created June 17, 2013 08:08
Show Gist options
  • Save superbob/5795355 to your computer and use it in GitHub Desktop.
Save superbob/5795355 to your computer and use it in GitHub Desktop.
Simple but powerfull Java TimeSpy. It wraps up a java method call in a spy class (method proxy) and records total elapsed time in successive calls. 1) [SpyInstanciations.java] Create an anonymous class extending TimeSpy which defines the run() method and returns something. 2) [SpyRuns.java] Run run(), instead of "your" method 3) [SpyResult.java]…
TimeSpy<Boolean> rsSpy = new TimeSpy<Boolean>() {
protected Boolean run() throws Exception {
return resultSet.next();
}
};
TimeSpy<Boolean> statementSpy = new TimeSpy<Boolean>() {
protected Boolean run() throws Exception {
return statement.execute();
}
};
TimeSpy<Boolean> commitSpy = new TimeSpy<Boolean>() {
protected Boolean run() throws Exception {
connection.commit();
return true;
}
};
long t1 = rsSpy.getTime()/1000000;
long t2 = statementSpy.getTime()/1000000;
long t3 = commitSpy.getTime()/1000000;
log.info("Ellapsed time : ResultSet.next() : " + t1 + "ms, Statement.execute() : " + t2 + "ms, Connextion.commit() : " + t3 + "ms.");
rsSpy.doIt()
statementSpy.doIt();
commitSpy.doIt();
private static abstract class TimeSpy<T> {
private long time = 0;
protected abstract T run() throws Exception;
public T doIt() throws InvocationTargetException {
time -= System.nanoTime();
T retVal;
try {
retVal = run();
} catch (Exception e) {
throw new InvocationTargetException(e);
}
time += System.nanoTime();
return retVal;
}
public long getTime() {
return time;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment