Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to calculate excuteion time for a line of code

 
raminaa niilian
Ranch Hand
Posts: 551
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?


Thanks
 
Tom Sullivan
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you talk yourself out of microseconds, see JAMon. The author hangs around the ranch.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic