// helping class to measure time import java.lang.Comparable; /** * Helper class to measure times. * Ajastin2 is the same but in Finnish language. */ public class DsaTimer implements Comparable { long start, end = 0L; String name = ""; String fform = "%.3f"; /** * Create new clock and start it */ public DsaTimer() { start = System.nanoTime(); } /** * Create new clock and start it * @param name name of the timer */ public DsaTimer(String name) { this(); this.name = name; } /** * Stop the clock * @return nanoseconds since start. */ public long stop() { end = System.nanoTime(); return (end - start); } /** * New start, reset time */ public void start() { start = System.nanoTime(); } /** * New start, do no reset time */ public void restart() { if (end != 0L) start = System.nanoTime() - (end - start); } // elapsed time in nanos /** * Time in nanoseconds since start or time used between start and stop if stopped * @return time used in nanoseconds. */ public long time() { long t = end - start; if (end == 0L) t += System.nanoTime(); return t; } /** * Time in nanoseconds since start or time used between start and stop if stopped * @return time used in nanoseconds. */ public long nanos() { long t = end - start; if (end == 0L) t += System.nanoTime(); return t; } /** * Time in microseconds since start or time used between start and stop if stopped * @return time used in microseconds. */ public double micros() { long t = end - start; if (end == 0L) t += System.nanoTime(); return t/1000.0; } /** * Time in milliseconds since start or time used between start and stop if stopped * @return time used in milliseconds. */ public double millis() { long t = end - start; if (end == 0L) t += System.nanoTime(); return t/(1000.0*1000.0); } /** * Time in seconds since start or time used between start and stop if stopped * @return time used in seconds. */ public double sek() { long t = end - start; if (end == 0L) t += System.nanoTime(); return t/(1000.0*1000.0*1000.0); } /** * compare two times, null is largest * @param b other timer * @return -1, 0, 1 */ public int compareTo(DsaTimer b) { if (b == null) return -1; if (this.time() < b.time()) return -1; else if (this.time() > b.time()) return 1; else return 0; } /** * equality of values * @param b * @return */ public boolean equals(DsaTimer b) { if (b == null) return false; if (this.time() == b.time()) return true; else return false; } /** * String representation of time, automatic time units. * @return */ public String toString() { long t = end - start; if (end == 0L) t += System.nanoTime(); String ts = null; if (t < 1000) ts = t + " ns"; else if (t < 100*1000) ts = String.format(fform, t/1000.0) + " us"; else if (t < 100*1000*1000) ts = String.format(fform, t/(1000.0*1000.0)) + " ms"; else ts = String.format(fform, t/(1000.0*1000.0*1000.0)) + " s"; return name + " " + ts; } }