• Java 2 Platform Standard Edition 5.0 API specification
• OpenJDK source code repository for library classes
• Source code from Data structures and problem-solving using Java, third edition
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.
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.countUp to count to one million.countUp to count to ten million.
Does this take ten times as long as counting to one million?