Monday, February 22, 2010

time taken to execute a Java Program

Hi Guys.......In this article i would describe to write a program in Java to calculate its execution time.

Its simple as follows:
  • Calculate time at beginning of the program execution.
  • Calculate time at the ending of the program.
  • Calculate the difference and display.
To calculate the time in millisecs, we use the method System.currentTimeMillis();

The above program looks perfectly fine and makes sense too!!! But there is a concept of static block in Java, where code inside a static block executes first.
Now you would say first line of code to be executed in java would be the one in main method. Why dont you try the following and see it for urself.

Output: this is from static block this is from main method:

Now, you might think the following code looks funny, but it does run.


Output: this is from static block this is from static block too!!

this is from main method:


Now this totally out of topic!!

But wait, this does make sense in using this concept in our program.
If you guessed that the starting time in millisec should be calculated in static block, then you are right...

Its simple as follows:

  • Calculate time at beginning of the program execution in static block.
  • Calculate time at the ending of the program (now you can say that the we can write this line in garbage collector block, but im not sure if we can override the garbage collector method. Even if we did find a way to do it, we cannot be sure if the code would be executed when we want it to be. Its controlled by virtual machine but when we want it to execute) .
  • Calculate the difference and display.



I agree that this does not achieve a significant precision, but this is the way to do it. Any comments are welcome if there is a better way other than this one.

No comments:

Post a Comment