Timing in Java
20 February 2004
6,043 Views
2 Comments
Here is a simple (homegrown) Timer class that I use to capture execution time in Java:
import java.io.PrintStream;
final class Timer
{
private long startTime;
private long endTime;
public Timer()
{
reset();
}
public void start()
{
System.gc();
startTime =
System.currentTimeMillis();
}
public void end()
{
System.gc();
endTime =
System.currentTimeMillis();
}
public long duration()
{
return (endTime - startTime);
}
public void printDuration( PrintStream out )
{
long elapsedTimeInSecond =
duration() / 1000;
long remainderInMillis =
duration() % 1000;
out.println("\nTotal execution time:"
+ elapsedTimeInSecond
+ "."
+ remainderInMillis
+ " seconds");
}
public void reset()
{
startTime = 0;
endTime = 0;
}
public static void main( String[] args )
{
Timer timer = new Timer();
timer.start();
for (int i = 0; i < 500; i++)
{
System.out.print("#");
}
timer.end();
timer.printDuration(System.out);
}
}









This worked for me, thanks!
Why do you have System.gc() in the end() method? I didn’t see the point of that one.
I probably had a good reason for the System.gc() 4 years ago when I posted this, but I can’t think of the reason off the top of my head now.
Leave your response!
Follow me on Twitter
Pages
Archives
Categories
Blogroll
Useful Websites
Tags
agile annotations apache build copyright design email etiquette farsi fit houston java javaranch jboss jbossinaction just-in-time kids language maven music myspace performance persian planning process quality recruiting refactoring response time scope screencast small teams smells startups startup weekend taxonomy tdd technical debt testing throughput universal velocity wiki xml xp