We return to a discussion of the elapsed time. The spec of class Date tells
you that this elapsed time can be obtained using this method in package
public static native long currentTimeMillis();
If all you want is this time in milliseconds, use this function.
Estimating execution time
Sometimes, it is useful to get some measure of how long it takes for a
method call to be executed. For example, one might want some understanding of
the difference in execution time of linear search and binary search (see Chap. 8).
However, the time is usually so short —less than a millisecond— that one can-
not get meaningful results from executing the method call once. So one might try
executing it m times, for m an integer like 10, or 100, or even 100000.
One can get the execution time in milliseconds using the following:
long startTime= System.currentTimeMillis();
Call the method m times;
long time= System.currentTimeMillis() - startTime;
The results of such a test cannot be relied on precisely because part of the
elapsed time may have been allocated to other functions that had to be executed.
The operating system on your computer switches between different applications
The way in which a number is printed using System.out.println(…) depends
on its size and type. The number of characters used, as well as the format, will
vary. Here are some examples:
The conversion of a number to a string for printing in such contexts is done
using a method toString in some class. In some situations, however, we would
like to control the string format of a number ourselves. Perhaps we want all inte-
gers to use the same number of digits —using either leading zeros or leading
spaces. Or, we might want double numbers to print always with two places to
the right of the decimal point.
Several classes of the Java API give us this capability.