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 use nanoTime( ) rather than currentTimeMillis( ). For example, here
is the key portion of the program rewritten to use nanoTime( ):
start = System.nanoTime(); // get starting time
for(int i=0; i < 1000000; i++) ;
end = System.nanoTime(); // get ending time
Using arraycopy( )
The arraycopy( ) 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 the arraycopy( ) method. First, a is copied to b.
Next, all of a's elements are shifted down by one. Then, b is shifted up by 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
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home