Home » Uncategorized

Timing in Java

20 February 2004 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);
}
}

2 Comments »

  • Timothy Boulan said:

    This worked for me, thanks!
    Why do you have System.gc() in the end() method? I didn’t see the point of that one.

  • Javid Jamae (author) said:

    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.