Timing in Java

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 Responses to “Timing in Java”

  1. Timothy Boulan Says:

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

  2. javid Says:

    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 a Reply