University stuff.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Timer.java 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import java.util.Arrays;
  2. class Timer implements Comparable<Timer> {
  3. public long time = 0;
  4. private long start = 0;
  5. Timer() {}
  6. Timer(long time) {
  7. this.time = time;
  8. }
  9. public Timer start() {
  10. start = System.nanoTime();
  11. return this;
  12. }
  13. public Timer end() {
  14. time = System.nanoTime() - start;
  15. return this;
  16. }
  17. public String prettyTime() {
  18. if (time < 1000)
  19. return String.format("%.2fns", time);
  20. else if (time < 1000000)
  21. return String.format("%.2fμs", time / 1000f);
  22. else if (time < 1000000000)
  23. return String.format("%.2fms", time / 1000000f);
  24. else
  25. return String.format("%.2fs", time / 1000000000f);
  26. }
  27. public String prettySpeedup(Timer base) {
  28. double speedup = (double)base.time / (double)time;
  29. return String.format("%s (%.2fx speedup)",
  30. prettyTime(), speedup);
  31. }
  32. public static Timer median(Timer[] timers) {
  33. Arrays.sort(timers);
  34. Timer med = new Timer();
  35. int mid = timers.length / 2;
  36. if (timers.length % 2 == 0)
  37. med.time = (timers[mid].time + timers[mid+1].time) / 2;
  38. else
  39. med.time = timers[mid].time;
  40. return med;
  41. }
  42. public int compareTo(Timer t) {
  43. if (this.time < t.time)
  44. return -1;
  45. else if (this.time > t.time)
  46. return 1;
  47. else
  48. return 0;
  49. }
  50. }