Java Reference
In-Depth Information
from Oracle's website, but is still available online . JavaOne 2010 featured an updated
presentation entitled “The Garbage Collection MythBusters.”
A timing program
It's pretty easy to build a simplified time command in Java, given that you have Sys-
tem.currentTimeMillis() to start with. Run my Time program, and, on the command line,
specify the name of the class to be timed, followed by the arguments (if any) that class needs
for running. The program is shown in Example 23-10 . The time that the class took is dis-
played. But remember that System.currentTimeMillis() returns clock time, not necessar-
ily CPU time. So you must run it on a machine that isn't running a lot of background pro-
cesses. And note also that I use dynamic loading (see Loading and Instantiating a Class Dy-
namically ) to let you put the Java class name on the command line.
Example 23-10. Time.java
public
public class
class Time
Time {
public
public static
throws Exception {
// Instantiate target class, from argv[0]
Class <?> c = Class . forName ( argv [ 0 ]);
static void
void main ( String [] argv ) throws
// Find its static main method (use our own argv as the signature).
Class <?>[] classes = { argv . getClass () };
Method main = c . getMethod ( "main" , classes );
// Make new argv array, dropping class name from front.
// (Normally Java doesn't get the class name, but in
// this case the user puts the name of the class to time
// as well as all its arguments...
String nargv [] = new
new String [ argv . length - 1 ];
System . arraycopy ( argv , 1 , nargv , 0 , nargv . length );
Object [] nargs = { nargv };
System . err . println ( "Starting class " + c );
// About to start timing run. Important to not do anything
// (even a println) that would be attributed to the program
// being timed, from here until we've gotten ending time.
// Get current (i.e., starting) time
long
long t0 = System . currentTimeMillis ();
// Run the main program
Search WWH ::




Custom Search