Lab exercise #6: Timing algorithms

Course links

External links

Measuring the running time of a method

The System.nanoTime method reads the computer's hardware clock and returns the value stored in the clock, converting it to a long. The unit of measurement in which the value is expressed is the nanosecond. One billion nanosections equal one second. (Since no MathLAN computer contains a hardware clock that is actually updated every nanosecond, the values that System.nanoTime returns on our systems should be regarded as inexact and approximate.)

To measure the running time of a method, call System.nanoTime and store the result in a long variable. Then immediately invoke the method. As soon as it returns, call System.nanoTime again and subtract the previous reading from the result. The difference will be the approximate running time of the method.

This measurement is also slightly biased towards high readings, because a certain amount of time is required to store the first reading in a variable, to set up for the method invocation, and to "tear down" when the method returns. In practice, this bias is often negligable.

  1. Write a CountingTime class containing a countUp method that simply initializes a local variable to zero and then increments it until some limit, specified by a parameter to countUp, is reached.
  2. Using the method described above, estimate how long it takes countUp to count to one million.
  3. Estimate how long it takes countUp to count to ten million. Does this take ten times as long as counting to one million?