Java Reference
In-Depth Information
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
java.lang.System :
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:
Lesson
page 5-6
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
(very quickly).
5.5
Formatting numbers
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:
System.out.println(5); 5
System.out.println(43); 43
System.out.println(23.56); 23.56
System.out.println(87654321.12345678); 8.765432112345678E7
System.out.println(.0000005); 5.0E-7
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.
Search WWH ::




Custom Search