views:

135

answers:

5

I have a program which i have myself written in java, but I want to test method execution times and get timings for specific methods. I was wondering if this is possible, by maybe somehow an eclipse plug-in? or maybe inserting some code?

I see, it is quite a small program, nothing more than 1500 lines, which would be better a dedicated tool or System.currentTimeMillis()?

Many thanks

+2  A: 

You should use a profiler like

They will easily integrate with any IDE and show whatever detail you need.

Of course these tools are complex and meant to be used to profile complex programs, if you need just some simple benchmarks I suggest you to use System.currentTimeMillis() or System.nanoTime() and calculate delta of millisecs between calls by yourself.

Jack
I see, it is quite a small program, nothing more than 1500 lines, which would be better a dedicated tool or System.currentTimeMillis()?
KP65
If you just need to check how fast some methods perform go with __System.currentTimeMillis()__, but mind that it's not precise at all! You can have quantization of tenths of millisecs and similar issues. Profiling is far more the best way to do what you need to do but it needs a little bit of learning.
Jack
+1  A: 

You can add this code and it will tell you how long the method took to execute.

long millisecondsStart = System.currentTimeMillis();
executeMethod();
long timeSpentInMilliseconds = System.currentTimeMillis() - millisecondsStart;
Shervin
Three problems. 1) the millisecond time may be quantized; e.g. to 20ms granularity. 2) you are actually measuring the time of `executeMethod()` + the time of `System.currentTimeMillis()`. 3) this does not account for JVM warmup effects; e.g. JIT compilation.
Stephen C
+1  A: 

Other than using a profiler, a simple way of getting what you want is the following:

public class SomeClass{
   public void somePublicMethod()
   {
       long startTime = System.currentTimeMillis();
       someMethodWhichYouWantToProfile();
       long endTime = System.currentTimeMillis();
       System.out.println("Total execution time: " + (endTime-startTime) + "ms"); 
   }
 }
Chris Knight
See my comments on @Sherwin's answer
Stephen C
@Stephen C - fair points. The above is the method I primarily use when trying to get a quick idea to method efficiency. My requirements in most cases aren't needed to single ms precision.
Chris Knight
A: 

Using a profiler is better because you can find out average execution times and bottlenecks in your app.

I use VisualVM. slick and simple.

Midhat
+1  A: 

Jprofiler and yourkit are good, but cost money.

There is a free plugin for eclispe called TPTP (Test & Performance Tools Platform) That can give you code execution times. Here is a tutorial that a quick google search brought up. http://www.eclipse.org/articles/Article-TPTP-Profiling-Tool/tptpProfilingArticle.html

Matt