package timing;

/**
 * Represents a action that we can time. This class is abstract,
 * and must be extended by implementing the {@code action} method.
 * @author ben
 */
public abstract class Timer {
	
	long ms = -1;
	double secs = -1.0;
    
    /**
     * Return the time in milliseconds it took to repeat the {@code action} method
     * {@code iteration} times.
     * 
     * @param iterations
     * @return the number of milliseconds it took for the iterated action to complete.
     */
    public long time(int iterations) {
    	long start = System.currentTimeMillis();
    	for (int i = 0; i < iterations; ++i) {
    		action();
    	}
    	long end = System.currentTimeMillis();
    	return ms = end - start;
    }
    
    /**
     * Return the time in seconds it took to repeat the {@code action} method
     * {@code iteration} times.
     * 
     * @param iterations
     * @return the number of seconds it took for the iterated action to complete
     */
    public double timeInSeconds(int iterations) {
    	return secs = time(iterations) / 1000.0;
    }
    
    /**
     * This represents some action to be repeated and timed.
     */
    public abstract void action();
    
    public void printResults(String message, int iterations) {
    	String s = message;
    	System.out.print(String.format("%1$-40s", s));
    	double seconds = timeInSeconds(iterations);
    	System.out.println(String.format("%.2f seconds", seconds));
    }
}
