58

I need to measure the time it takes for a function to complete in Java. How can I do that?

Note:

I want to measure the function's time consumption, not that of the full program.

Community
  • 1
  • 1
fmsf
  • 36,317
  • 49
  • 147
  • 195

9 Answers9

109
long start = System.nanoTime();    
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;
Ande Turner
  • 7,096
  • 19
  • 80
  • 107
  • 3
    Note that the clock that nanoTime is polling is probably NOT accurate to the nanoSecond. If you're lucky, the accuracy will be the clock speed of your CPU, otherwise it will be some multiple of that. – Paul Tomblin Mar 28 '09 at 11:24
  • 1
    If you need to time your function in nanoseconds, perhaps it's already fast enough? I just got annoyed by dividing everything by 1 *billion* to see how many seconds it was. – Noumenon Aug 14 '15 at 23:14
  • I make this and the precision was more exactly than using a timer (starting the timer just before the methodToBeTimed() and stop just after the methodToBeTimed) – Ignacio Chiazzo Aug 17 '15 at 23:57
53

Here is how can compute the elapsed time.

// Get current time
long start = System.currentTimeMillis();

// Do something ...

// Get elapsed time in milliseconds
long elapsedTimeMillis = System.currentTimeMillis()-start;

// Get elapsed time in seconds
float elapsedTimeSec = elapsedTimeMillis/1000F;

// Get elapsed time in minutes
float elapsedTimeMin = elapsedTimeMillis/(60*1000F);

// Get elapsed time in hours
float elapsedTimeHour = elapsedTimeMillis/(60*60*1000F);

// Get elapsed time in days
float elapsedTimeDay = elapsedTimeMillis/(24*60*60*1000F);
Christian Stade-Schuldt
  • 4,671
  • 7
  • 35
  • 30
10

If you are using Guava, consider using the Stopwatch, e.g.:

final Stopwatch sw = Stopwatch.createStarted();
methodToBeTimed();
final long elapsedMillis = sw.elapsed(TimeUnit.MILLISECONDS);
Jonathan
  • 20,053
  • 6
  • 63
  • 70
9

Use a profiler.

Aaron Maenpaa
  • 119,832
  • 11
  • 95
  • 108
6

The profiler is the right answer if you have more than one function.

Another problem that I see with all the suggestions given so far is that they work fine for a single function, but your code will be littered with timing stuff that you can't turn off.

If you know how to do aspect oriented programming, it's a good way to keep the timing code in one place and apply it declaratively. If you use something like Log4J to output the values, you'll have the option of turning it off or on. It's a poor man's profiler.

Have a look at AspectJ or Spring's AOP.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • I agree that a profiler is overkill if you only want to time *one* function; however, even if you start out only wanting to time one function you generally end up timing more than that. – Aaron Maenpaa Mar 30 '09 at 18:42
5

All of the code snippets above measure the approximate time elapsed from the time the method was invoked to the time the method returns/throws an exception. Such techniques do not address thread scheduling, pauses due the GC, etc.

Yes, some profilers will do a reasonable job.

If you are using Java 1.6 onwards, you can use the JMX based VM management and monitoring support. For example, you may find ThreadMXBean.getCurrentThreadCpuTime() of value. Calculating the difference of this value before and after the method invoke will give you:

"... the total CPU time for the current thread in nanoseconds. The returned value is of nanoseconds precision but not necessarily nanoseconds accuracy. If the implementation distinguishes between user mode time and system mode time, the returned CPU time is the amount of time that the current thread has executed in user mode or system mode."

If your method spawns off worker threads, then your computation will need to get far more elaborate ;-)

In general, I recommend nosing around the java.lang.mangement package.

Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52
4

System.nanoTime should be used to accurately measure the delta between two times for microbenchmarks.

public class CountTime {

  private static void walk() {
    for (int i = 0; i < Integer.MAX_VALUE; i++)
      ;
  }

  public static void main(String[] args) {
    long t0 = System.nanoTime();
    walk();
    long t1 = System.nanoTime();
    System.out.println("Elapsed time =" + (t1 - t0)
        + " nanoseconds");
  }

}

System.currentTimeMillis returns the current time in milliseconds. You can use this to get the current time. This may be useful on older VMs or for longer running processes.

McDowell
  • 107,573
  • 31
  • 204
  • 267
3

Use either System.currentTimeMillis() or System.nanoTime():

int someMethod() {
    long tm = System.nanoTime();
    try {
        ...
    } finally {
        tm = System.nanoTime()-tm;
        System.out.println("time spent in someMethod(): " + tm + "ns");
    }
}
Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
0

this analogue stopwatch is another option for us too... Check on Java2s.com here.

gumuruh
  • 2,544
  • 4
  • 33
  • 56