How To Accurately Test Your Java Speed And Precision


Vaibhav Pandey By: Vaibhav Pandey

I don’t think you need to compute your program execution time everytime you execute your program but sometimes when you need to compare performance then it becomes necessary to compute the execution time. When you need to compare programming styles then you may consider calculating the time required by each program to complete the task, shorter the time ir the faster the program is. Since processors are much faster now and new RAM is capable of millions of loops complete within a split second. There is a need to calculate speed and the precision of 1000th of a second. In order to compute the time used we call currentTimeMillis() method of System class which returns current time of your computer system. There is a very simple logic which is implemented to create this utility.

In the following example we will compute the program execution time of main() method. As we enter the main() method we will compute the system time and after implementation of programming logic or business logic we will again compute the system time. Remember the system time is returned as long in milliseconds. So now you have two values first when we started our main() method and second just before exiting the main. We assume here is that the program exits immediately after getting second value.

Source code and Example:-

// Method to be used System. currentTimeMillis()
//This method returns long values.

class timecalc
{
public static void main(String a[]){
long time = System. currentTimeMillis();
System. out. println(time);
for(int i=0;i<5000000;i++)
{
for(int j=0;j<1000;j++);
}
long end = System. currentTimeMillis();
System. out. println(end-time);
}
}

Output :-
3782
Remember the output may vary according to your computers speed. speed is affected by various factors like RAM,processor speed,running programs,cache etc.

Here in above example I have taken such long loop because just to calculate the time difference and to just give you a demo how things goes. When you compute for several hundreds of values then it is possible that it might return 0. Everytime your run your program and you are expected to get a different value.

Comments

About The Author

Vaibhav Pandey got offered employment from an Indian Multinational IT Company. He is 21 years old. He has a huge interest in Java programming and has liked it from his study days. Vaibhav loves to blog and share his experiences and thoughts. He now resides in Lucknow, a state capital in India. Check out his blog at http://javatutorialsworld.blogspot.com.

Comments are closed.

















Get Your Site
Submitted for Free
in the World's Largest
B2B Directory!

Email Address:
*URL:
*
*Indicates Mandatory Field
Terms & Conditions