how to calculate excuteion time for a line of code
Joined: Jul 14, 2005
Thank you for reading my post Is there any way to calculate the time that an statement take to execute? I want the time to be calculated in MIcrosecond not in millisecods. is there any way to do this ?
Joined: Dec 20, 2005
I have never tried such a thing but, could you do:
long start = System.nanoTime(); MyObject.run(); long total = System.nanoTime() - start;
Then if you want to convert the time, multiply or divide by whatever constant you need for the conversion?
You could probably do the same in milliseconds with System.currentTimeMillis().
Joined: Oct 30, 2001
This is only feasible if the line that you want to time is going to take quite a while to execute. By quite a while, I guess I mean tens of milliseconds. For most single lines of code, you have no chance of getting an accurate timing, because they execute very fast and the timing is not that accurate; often the timing code would actually take longer to run than the single line you're trying to time!
Note that nanoTime() does not necessarily get you what you want. Sure, it has nanosecond precision, but that does not mean it has nanosecond accuracy. Consider a cheap digital stop-watch. It may well display the runner's time to hundredths of a second, but the inaccuracy of the watch, combined with the difficulty of pressing the buttons at exactly the right time, means that the accuracy will never be better than a few tenths of a second.
Perhaps one should ask what you wish to achieve by timing a single statement? [ February 27, 2006: Message edited by: Peter Chase ]
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
Joined: Jan 29, 2003
If you talk yourself out of microseconds, see JAMon. The author hangs around the ranch.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi