I need to perform the same operation using two different ways of doing it, and I need to show which method was more efficient. I've been told there's a way to time these methods using something like system timers. Does anybody know how this is done? I'm assuming I need to run a line of code before and after each method and compare the results.
Greg Roberts<br />CIS Student<br />University of West Florida
Joined: Aug 20, 2001
The easiest way is to use System.currentTimeMillis()
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Be aware that System.currentTimeMillis() is not very accurate, and milliseconds can be quite long if you're talking about code running on a computer. So the currentTimeMillis() method will only really be useful if the methods take a relatively long time to execute.
If you are using Java 5, you could try using System.nanoTime(), which might be more accurate (depending on the system you're using!). See the API documentation.
Also, be aware that the Java VM might compile your byte code to native code using the JIT, so if you call the same method multiple times, it might run faster the second, third etc. time than the first time. Ideally, you should run each method that you want to test a large number of times and calculate the average execution time:
If the operations you're comparing complete so quickly that you can't see the difference at millisecond granularity, try running them multiple times (say, 10,000 times) in loops & compare the cumulative results.
Joined: Feb 05, 2005
I'm getting an error that I can't seem to trace. In the code:
I'm getting "Unreachable code" on endTime = System.nanoTime(); Why is this code unreachable?
P.S. This is part of a program to generate a Fibonacci number. The above code is from the method using iteration. [ November 18, 2005: Message edited by: Greg Roberts ]
Joined: Sep 16, 2005
Stare at these two lines!
There is no emoticon for what I am feeling!
Joined: Feb 05, 2005
Yeah, I guess it would help if the system time method was called before the return statement, wouldn't it?
I've got another problem. I'm getting stack overflow errors with my recursive method:
Its a program to compute Fibonacci numbers, but I've never programmed with recursion before. Can anybody tell me where I'm going wrong here? [ November 19, 2005: Message edited by: Greg Roberts ]