Tech and Media Labs
This site uses cookies to improve the user experience.




Java Time Measurement

Jakob Jenkov
Last update: 2014-06-23

Measuring time in Java is easiest to do with the System.currentTimeMillis() method.

What you do is that you get the time before and after the operation you want to measure, and calculate the time difference. Here is an example:

long startTime = System.currentTimeMillis();

callOperationToTime();

long endTime   = System.currentTimeMillis();

long totalTime = endTime - startTime;

The variable totalTime will now contain the total time it took to execute the callOperationToTime() method.


Repeat the Operation

Because System.currentTimeMillis() does not return the time that accurately, it is a good idea to execute the operation to measure more than once. Perhaps 10, 100 or 1.000 times. Maybe even more. That way inaccuracy caused by large grained time values (values that does not change every millisecond) is leveled out.

Another good reason to repeat the operation to measure a lot of times is to allow the Java virtual machine to load the classes containing the code, JIT-compile it, and perhaps even optimize it.


A Timer class

The calculations listed earlier in this text are rather trivial yet tedious to do, and could be encapsulated in a Timer class. Here is a sketch:

public class Timer {

  private long startTime = 0;
  private long endTime   = 0;

  public void start(){
    this.startTime = System.currentTimeMillis();
  }

  public void end() {
    this.endTime   = System.currentTimeMillis();  
  }

  public long getStartTime() {
    return this.startTime;
  }

  public long getEndTime() {
    return this.endTime;
  }

  public long getTotalTime() {
    return this.endTime - this.startTime;
  }
}

Here is an example of how to use it:

Timer timer = new Timer();

timer.start();

callOperationToTime();

timer.end();

long totalTime = timer.getTotalTime();

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC