package ch.cern.it.util;

/**
 * A handy stopwatch for benchmarking.
 * Like a real stop watch used on ancient running tracks you can start the watch, stop it,
 * start it again, stop it again, display the elapsed time and reset the watch.
 */
public class Timer extends Object implements java.io.Serializable {
	private long baseTime;
	private long elapsedTime;

	private static final long UNIT = 1000;
/**
 * Constructs a new timer, initially not started. Use start() to start the timer.
 */
public Timer() {
	this.reset();
}
/**
 * Prints the elapsed time on System.out
 */
public Timer display() {
	System.out.println(this);
	return this;
}
/**
 * Returns the elapsed time in seconds.
 */
public float elapsedTime() {
	return ((float) elapsedTime) / UNIT;
}
/**
 * Resets the timer.
 */
public Timer reset() {
	elapsedTime = 0;
	baseTime=0;
	return this;
}
/**
 * Starts the timer.
 */
public Timer start() {
	baseTime = System.currentTimeMillis();
	return this;
}
/**
 * Stops the timer. You can start it again later, if necessary.
 */
public Timer stop() {
	if (baseTime==0) {
		throw new RuntimeException("Can't stop a timer more than once without starting it again.");
	}
	elapsedTime = elapsedTime+ (System.currentTimeMillis() - baseTime);
	return this;
}
/**
 * Shows how to use a timer in convenient ways.
 */
public static void test(int size) {
	//benchmark this piece
	Timer t = new Timer().start(); 
	int j=0;
	for (int i=0; i<size; i++) {
		j++;
	}
	t.stop();
	t.display();
	System.out.println("I finished the test using "+t);

	

	//do something we do not want to benchmark
	j=0;
	for (int i=0; i<size; i++) {
		j++;
	}


	
	//benchmark another piece and add to last benchmark
	t.start();
	j=0;
	for (int i=0; i<size; i++) {
		j++;
	}
	t.stop().display();

	

	//benchmark yet another piece independently
	t.reset(); //set timer to zero
	t.start();
	j=0;
	for (int i=0; i<size; i++) {
		j++;
	}
	t.stop().display();
}
/**
 * Returns a String representation of the receiver.
 */
public String toString() {
	return "Time=" + Float.toString(this.elapsedTime()) + " secs";
}
}