Skip to content

Instantly share code, notes, and snippets.

@mortie
Created March 10, 2017 21:21
Show Gist options
  • Save mortie/cde0af95c2a6f8f0a8704420619f4346 to your computer and use it in GitHub Desktop.
Save mortie/cde0af95c2a6f8f0a8704420619f4346 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
class Timer implements Comparable<Timer> {
public long time = 0;
private long start = 0;
public Timer start() {
start = System.nanoTime();
return this;
}
public Timer end() {
time = System.nanoTime() - start;
return this;
}
public String prettyTime() {
if (time < 1000)
return String.format("%.2fns", time);
else if (time < 1000000)
return String.format("%.2fμs", time / 1000f);
else if (time < 1000000000)
return String.format("%.2fms", time / 1000000f);
else
return String.format("%.2fs", time / 1000000000f);
}
public String prettySpeedup(Timer base) {
double speedup = (double)base.time / (double)time;
return String.format("%s (%.2fx speedup)",
prettyTime(), speedup);
}
public static Timer median(Timer[] timers) {
Arrays.sort(timers);
Timer med = new Timer();
int mid = timers.length / 2;
if (timers.length % 2 == 0)
med.time = (timers[mid].time + timers[mid+1].time) / 2;
else
med.time = timers[mid].time;
return med;
}
public int compareTo(Timer t) {
if (this.time < t.time)
return -1;
else if (this.time > t.time)
return 1;
else
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment