Skip to content

Instantly share code, notes, and snippets.

@relekang
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save relekang/c3e96dd9455434c84c49 to your computer and use it in GitHub Desktop.
Save relekang/c3e96dd9455434c84c49 to your computer and use it in GitHub Desktop.
A Runnable timer in java

Usage

new Timer(new Runnable() {
    @Override
    public void run() {
        // Time consuming code
    }
}, 1000).run().report();
public class Timer {
private final Runnable task;
private final int n;
private long sum;
private long highest = 0;
private long lowest = 0;
public Timer(Runnable task, int n) {
this.task = task;
this.n = n;
this.sum = 0;
}
public Timer run() {
for (int i = 0; i < n; i++) {
long started = System.currentTimeMillis();
task.run();
long ended = System.currentTimeMillis();
long time = ended - started;
sum += time;
if (time > highest) highest = time;
if (time < lowest) lowest = time;
}
return this;
}
public void report() {
System.out.println(String.format(
"Average Execution time: %dms.\nHighest: %dms\nLowest: %dms",
sum / n,
highest,
lowest
));
}
public void csv() {
System.out.println(String.format(
"%d,%d,%d,%d",
n,
sum / n,
highest,
lowest
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment