new Timer(new Runnable() {
@Override
public void run() {
// Time consuming code
}
}, 1000).run().report();
Last active
August 29, 2015 14:10
-
-
Save relekang/c3e96dd9455434c84c49 to your computer and use it in GitHub Desktop.
A Runnable timer in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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