Timing your Java program

You may use the System function currentTimeMillis to time your java program. Here is a description of the function from Sun's java pages:
currentTimeMillis public static long currentTimeMillis()

Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.


Here is a small program that tests this function.
class TestTiming
{
        public static void main(String[] args)
        {
                int j;
                long begintime, endtime; 

                begintime = System.currentTimeMillis();

                for(int i = 0; i < 10000; i++)
                        j = i;

                endtime = System.currentTimeMillis();

                System.out.println("It took "+(endtime-begintime)+" msec");
        }
}

If you get 0 as an answer you may execute the code you are timing a large number of times, say N, measure how long it takes to execute it N times and divide the result by N. The following program illustrates this.

class TestTiming
{
        public static void main(String[] args)
        {
                int j;
                long begintime, endtime;
		int N=10000;
		double result;

                begintime = System.currentTimeMillis();

                for(int i = 0; i < N; i++)
                {
                   .. put your code here ...
                }        

                endtime = System.currentTimeMillis();
		result = (double)(endtime-begintime)/N;

                System.out.println("It took "+result+" msec");
        }
}