Fundamental to development of programs that perform any kind of time intensive task is the ability to measure how much time execution takes. Here’s a simple Java class to measure elapsed time:
package codeZach.utils.timing;
public class ElapsedTimer
{
protected long start = 0;
protected long elapsed = 0;
public void start() throws Exception
{
if(this.start > 0)
{
throw new Exception("Timer already started");
}
this.start = System.nanoTime();
this.elapsed = 0;
}
public boolean isRunning()
{
if(this.start == 0)
{
return false;
}
return true;
}
public long getElapsed()
{
if(this.isRunning() == false)
{
return this.elapsed;
}
long ret = (System.nanoTime() - this.start) / 1000000;
return ret;
}
public void stop() throws Exception
{
if(this.isRunning() != true)
{
throw new Exception("Timer never started");
}
this.elapsed = this.getElapsed();
this.start = 0;
}
public void reset() throws Exception
{
this.start = 0;
this.elapsed = 0;
}
public void restart() throws Exception
{
this.reset();
this.start();
}
@Override
public String toString()
{
String ret = Long.toString(this.getElapsed()) + "ms";
return ret;
}
}
There are a couple of basic ways to use this timer, illustrated in the example below. The first is just simple elapsed time, the second is to time series of loop iterations.
package codeZach.entryPoint;
import codeZach.utils.timing.ElapsedTimer;
public class EntryPoint {
/**
* @param args
*/
public static void main(String[] args) throws Exception
{
ElapsedTimer et = new ElapsedTimer();
ElapsedTimer it = new ElapsedTimer();
et.start();
it.start();
for(int i = 0; i < 1000000000; i++)
{
int j = i + 100;
j++;
if(i % 1000000 == 0)
{
System.out.println("Iteration completed in: " + it);
it.restart();
}
}
System.out.println("Completed in: " + et);
}
}
The results of running this are:
... Iteration completed in: 4ms Iteration completed in: 6ms Iteration completed in: 4ms Iteration completed in: 4ms Iteration completed in: 4ms Iteration completed in: 6ms Iteration completed in: 4ms Iteration completed in: 5ms Iteration completed in: 4ms Completed in: 5171ms

April 18th, 2009 5:18 pm
Ugh, I liked! So clear and positively.