Sunday, February 19, 2017

MeteredSorter

abstract class MeteredSorter<T extends Comparable<T>>
extends Sorter<T> implements IMetered {

  private Meter meter;
  private long startReading, endReading;
  private long startTime, endTime;

  // Constructors

  public MeteredSorter() {
    meter = new Meter();
  }
  public MeteredSorter(Meter m) {
    meter = m;
  }

  // Private metering methods

  private void startMetering() {
    startReading = meter.reading();
    startTime = System.nanoTime();
  }
  private void stopMetering() {
    endTime = System.nanoTime();
    endReading = meter.reading();
  }

  // IMetered methods

  public boolean tick() {
    meter.tick();
    return true;
  }
  public long unitsCounted() {
    return endReading - startReading;
  }
  public long timeConsumed() {
    return endTime - startTime;
  }

  // ISort methods

  public T[] sort(T[] seq)
  throws IllegalArgumentException {
    startMetering();
    super.sort(seq);
    stopMetering();
    return seq;
  }

  public T[] sort(T[] seq, int from, int to)
  throws IllegalArgumentException, IndexOutOfBoundsException {
    startMetering();
    super.sort(seq, from, to);
    stopMetering();
    return seq;
  }
}