ACCESSING THE SYSTEM CLOCK

(and other system fields and methods)

CONTENTS

1. Introduction
2. Example
3. the err object


1. INTRODUCTION

It is sometimes of interesdt to be able to time the duratuion of algorithm by including in the code a call to the system clock prior to commencement (time1) and imeediatley on completion (time2) duration can then be calculated bu subtracting time 1 from time 2. Thus

time1 = access system clock

Run algorithm

time2 = access system clock

duration = time2-time1

The class System has a method currentTimeMillis which returns (as a long integer) the current time in milliseconds. This can thus usefully be employed to determine the "rum time" of algorithms.



2. EXAMPLE

In Table 1 we present an implementation of the above (timing the initilisation of a sequence of different sizes of array in steps of 10000). Some output is presented in Table 2 (predictivly the increase in diration is linear).

// Timing Experiment
// Frans Coenen
// 21 May 2000
// Dept Computer Science, University of Liverpool

class TimingExp {  
    
    /* MAIN */
    
    public static void main(java.lang.String [] args) {
        long time1, time2, duration;
	int[] intArray = null;
	int counter;
	
        for (int index = 10000;index <= 100000;index=index+10000) {
	    time1 = System.currentTimeMillis(); 
	    intArray = new int[index];
	    for (counter=0;counter < index;counter++) intArray[counter] = 
	    			counter;
	    time2 = System.currentTimeMillis();			
	    duration = difference(time1,time2);
	    System.out.println("Array size = " + index + " duration = " + duration);
	    }
        }

    /* DIFFERENCE */
    
    public static long difference(long tm1, long tm2) {
        return((tm2-tm1));
	}
    }

Table 1:Example method

$ java TimingExp
Array size = 10000 duration = 6
Array size = 20000 duration = 11
Array size = 30000 duration = 17
Array size = 40000 duration = 23
Array size = 50000 duration = 29
Array size = 60000 duration = 47
Array size = 70000 duration = 52
Array size = 80000 duration = 59
Array size = 90000 duration = 64
Array size = 100000 duration = 72         

Table 2:Output from example code presented in Table 1



3. THE err OBJECT

The err object is a PrintStream object describing the "standard error output stream". It is used in the same way as the out object:

System.err.print("ERROR 1: ");
System.err.println("Undefined error.");



Created and maintained by Frans Coenen. Last updated 19 January 2001