• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Execution time

 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I want to find the time taken by some of the functions in my code. The following is the sample code i have written to compute the time. I wanted to know whether this is the proper way of doing it.



Also, is there a way to find the time in micro seconds?
 
Carey Brown
Ranch Hand
Posts: 1533
18
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically your code is correct.
There is also a System.nanoTime() method.
And, your for() loop as written may be optimized away.
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,

Thanks for the prompt reply. Can you expand a bit more on the optimization thing. Probably, some useful resources?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that the resolution of currentTimeMillis() is not very good on all operating systems - on some systems the timer goes in steps of 50 ms, which is too long to time quick running methods.

Also note that the JVM does a lot of sophisticated optimizations and that makes timing your code this way very hard. The JVM will most likely throw away the empty loop in your method completely, because it's smart enough to understand that the loop has no effect at all. You then think you are timing the loop, while in reality the loop isn't even run at all.

If you really want to measure the performance of your code, use profiling software instead of trying to do it with a timer yourself. Note that the JDK includes a tool for this, JVisualVM.

Read this article to get an idea of how tricky it is to measure the performance of Java programs:
Dynamic compilation and performance measurement
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all. Now i understood why i was always getting 0 as the execution time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic