views:

279

answers:

8

I frequent wrap code in a System.nanoTime() pair in order to timing it. Something like:

long start = System.nanoTime();    
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;

There is any good timing library that helps with this problem? Also homegrown code will be accepted.

NB

A profiler is not a solution here, since I want to enforce some time constraints in my unit tests, so I want to timing methods programmatically.

+1  A: 

Not a direct answer to your question, but I am also often using this tip to time my code and just wrote the following simple Eclipse -> Surround With template:

long startTime = System.currentTimeMillis();
${line_selection}${cursor}
long totalTime = System.currentTimeMillis() - startTime;
System.out.println("Total time = " + totalTime);
System.out.println();
Manuel Selva
unfortunately I'm a netbeans user -:)
dfa
A: 

Tried JPerf ?

techzen
Use google cache to see usage, Alternatively check the link to xjperf: http://code.google.com/p/xjperf/
techzen
it seems a frontend for iperf, that is "a modern alternative for measuring maximum TCP and UDP bandwidth performance". It is right?
dfa
+1  A: 

What kind of help are you looking for with this problem? You have the basics in place. You get the elapsed time in Nanoseconds, accurate to whatever resolution the underlying OS/Hardware is capable of.

Also... and I know you said no profilers... but I have had outstanding experience with YourKit. It provides an API that you can use to control profiling from the outside. Depending on what your exact problem is, this one might be worth having a look at.

Eric J.
+3  A: 

there is StopWatch from commons-lang, it also allows you to split timer.

01
nice to see it but it only encapsulates System.nanoTime/System.currentTimeMillis calls
dfa
its always easier to use than the default version ;)
01
+4  A: 

JUnit 4 got a built-in timing-contraint funtionality.

@Test(timeout=X)

should do the trick. X is the maximum number of milliseconds the method is allowed to run.

Philipp
Sounds like a winner to me.
Bill K
yes, this is a very basilar implementation, essentialy I'm loooking for @Test(timeout=X, repeat=N) then display the average
dfa
+1  A: 

I haven't used it but I came across perf4j recently.

Mark
@Mark: never heard about it. Thanks very much!
dfa
+2  A: 

If you're using Spring you already have nice class called StopWatch in your classpath for this propose.

Malax