Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
start = System.currentTimeMillis(); // get starting time
for(int i=0; i < 1000000; i++) ;
end = System.currentTimeMillis(); // get ending time

System.out.println("Elapsed time: " + (end-start));
}
}


Here is a sample run (remember that your results probably will differ):


Timing a for loop from 0 to 1,000,000
Elapsed time: 10

If your system has a timer that offers nanosecond precision, then you could rewrite the
preceding program to usenanoTime( )rather thancurrentTimeMillis( ). For example, here
is the key portion of the program rewritten to usenanoTime( ):


start = System.nanoTime(); // get starting time
for(int i=0; i < 1000000; i++) ;
end = System.nanoTime(); // get ending time


Using arraycopy( )


Thearraycopy( )method can be used to copy quickly an array of any type from one place to
another. This is much faster than the equivalent loop written out longhand in Java. Here is
an example of two arrays being copied by thearraycopy( )method. First,ais copied tob.
Next, all ofa’s elements are shifteddownby one. Then,bis shiftedupby one.


// Using arraycopy().


class ACDemo {
static byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
static byte b[] = { 77, 77, 77, 77, 77, 77, 77, 77, 77, 77 };


public static void main(String args[]) {
System.out.println("a = " + new String(a));
System.out.println("b = " + new String(b));
System.arraycopy(a, 0, b, 0, a.length);
System.out.println("a = " + new String(a));
System.out.println("b = " + new String(b));
System.arraycopy(a, 0, a, 1, a.length - 1);
System.arraycopy(b, 1, b, 0, b.length - 1);
System.out.println("a = " + new String(a));
System.out.println("b = " + new String(b));
}
}


As you can see from the following output, you can copy using the same source and destination
in either direction:


a = ABCDEFGHIJ
b = MMMMMMMMMM

Chapter 16: Exploring java.lang 411

Free download pdf