Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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();

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

@Test(timeout=X)

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

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

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

Tried JPerf ?

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.

Caliper

And in addition to reading the wikis on that site, i recommend reading:

JETM is a good library for doing this. It can also provide with mins, maxs and averages, plus can generate informative graphs.

handmade...

import static java.lang.System.nanoTime;

/**
 * For testing / debug purposes.
 * 
 * <pre>
 *  private Stopwatch stopwatch = new Stopwatch();
 *  ...
 *  public void method1() {
 *      stopwatch.reset();
 *      for (...) {
 *          ...
 *          stopwatch.start();
 *          operation1();
 *          stopwatch.stop();
 *          ...
 *      }
 *      System.out.println("operation 1 max timing is " + stopwatch.getMaxLapTime());
 *  }
 *  ...
 *  public void method2() {
 *      stopwatch.reset();
 *      for (...) {
 *          ...
 *          stopwatch.start();
 *          operation2();
 *          stopwatch.stop();
 *          ...
 *      }
 *      System.out.println("operation 2 max timing is " + stopwatch.getMaxLapTime());
 *  }
 * </pre>
 * 
 * @author Mykhaylo Adamovych
 */
public class Stopwatch {
    protected long totalTime;
    protected long maxLapTime;
    protected long minLapTime = Long.MAX_VALUE;
    protected long lapsCount;
    protected long lastThreshold;

    /**
     * Human readable time in seconds
     * 
     * @param nanoTime
     * @return time in seconds
     */
    public static final String toSeconds(long nanoTime) {
        return String.format("%.9f", nanoTime / 1000000000.0);
    }

    public long getAverageLapTime() {
        if (lapsCount == 0)
            return 0;
        return totalTime / lapsCount;
    }

    public long getMaxLapTime() {
        return maxLapTime;
    }

    public long getMinLapTime() {
        return minLapTime;
    }

    public long getTotalTime() {
        return totalTime;
    }

    /**
     * Returns last lap time, process statistic.
     */
    public long lapTime() {
        return processLapTime();
    }

    private long processLapTime() {
        if (lastThreshold == 0)
            throw new IllegalStateException("Stopwatch is stopped.");
        final long now = nanoTime();
        final long lapTime = now - lastThreshold;
        lapsCount++;
        totalTime += lapTime;
        if (lapTime > maxLapTime)
            maxLapTime = lapTime;
        if (lapTime < minLapTime)
            minLapTime = lapTime;
        lastThreshold = nanoTime();
        return lapTime;
    }

    /**
     * Resets statistic and starts.
     */
    public void reset() {
        totalTime = 0;
        maxLapTime = 0;
        minLapTime = Long.MAX_VALUE;
        lapsCount = 0;
        start();
    }

    /**
     * Starts time watching.
     */
    public void start() {
        lastThreshold = nanoTime();
    }

    /**
     * Suspends time watching, returns last lap time.
     */
    public long stop() {
        final long lapTime = processLapTime();
        lastThreshold = 0;
        return lapTime;
    }
}

Something new on the market is JMH. It's made under the umbrella of the openjdk project.

I've just started using Java Simon (formerly on Google Code), and it seems awesome! A simple set of stopwatches and counters with few dependencies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top