Java

INDEPENDENT TOPIC 05 – TIMING

 

 

LESSON NOTE

 

 

APPROACH 1 – System.nanoTime()

 

One can use System.nanoTime() to get an initial nanosecond reading.  Note that alone, this value is not valuable.  But if we take a second reading, we can then take the difference between the two values and that will be the time in nano seconds that has passed between the readings.

 

Note that nanoseconds are very small amounts of time.  So we tend to have very big numbers when we deal with a measurement of time in nanoseconds.  Therefore, instead of using int variables, we use long variables.

 

EXAMPLE CODE

 

The following example takes two readings and stores thoses values in t1 and t2.  The difference of the two readings in the elapsed time between readings in nano seconds.

 

long t1 = System.nanoTime();

 

//Add some statements here

 

long t2 = System.nanoTime();

 

long dif = t2 – t1;

 

System.out.println("The time that has passed is " + dif + " nanoseconds. ");

 

APPROACH 2 – System.currentTimeMillis()

 

One can also use System.currentTimeMillis() to get the number of milliseconds that have passed since January 1st 1970.  While a single reading is usable, we still tend to use this at take the difference between two readings to get the elapsed time in milliseconds.

 

EXAMPLE CODE

 

Below you will find the exact same approach as above but for milliseconds.

 

long t1 = System.currentTimeMillis();

 

//Add some statements here

 

long t2 = System.currentTimeMillis();

 

long dif = t2 – t1;

 

System.out.println("The time that has passed is " + dif + " milliseconds. ");

 

CONVERTING TO SECONDS

 

We can convert nanoseconds to seconds by dividing by 1,000,000,000 (one billion).

We can convert milliseconds to seconds by dividing by 1000 (one thousand).