4/8/08

Excecution time in Java

I am going to write my answer to the question " HOW DO I CALCULATE ELAPSED TIME IN JAVA ?"
As far as I now there are two simple ways to calculate the elapsed time - excecution time in JAVA programming language.
Java gives two methods ,nanoTime() and currentTimeMillis() both declared in class java.lang.System .
currentTimeMillis() returns the current time in milliseconds (long) and (as expected) nanoTime() returns the current value of the most precise available system timer in nanoseconds (long).
Below you can see an example of how to calculate the excecution time of a method. The example bellow calculate excecution time of a simple method which it's just a for loop which print numbers from 0 to 1000 but it can be any method you want.

First I used System.currentTimeMillis() to calculate the elapsed time and then System.nanoTime().

import java.lang.String;

public class time_example {

public static void print_num(){
for(int i = 0 ; i<=1000 ; i++) {
System.out.print(i+" ");
}
System.out.println();
}

public static void main(String args[]) {

long start,end;
start = 0; end = 0;

start = System.currentTimeMillis();
print_num();
end = System.currentTimeMillis();
System.out.println("Elapsed time (approximately)
in milliseconds = " +(end-start));

start = System.nanoTime();
print_num();
end = System.nanoTime();
System.out.println("Elapsed time (approximately)
in nanoseconds = " +(end-start));
}
}

And the output is :

0 1 2 3 4 5 ... 995 996 997 998 999 1000
Elapsed time (approximately) in milliseconds = 47
0 1 2 3 4 5 ... 995 996 997 998 999 1000
Elapsed time (approximately) in nanoseconds = 193986945

You may also want to see Elapsed Time in C.
I hope that this post was helpful and don't forget to post your comments. Thank you.

No comments: