Is there a command in java to measure the execution time?

user680406 picture user680406 · Mar 29, 2011 · Viewed 11.3k times · Source

Is there a command in java to measure the execution time ?

Something like

System.out.println(execution.time);

in the end of the code.

Answer

RoflcoptrException picture RoflcoptrException · Mar 29, 2011

Here is a complete and little modified example on how you could do that:

public class ExecutionTimer {
  private long start;
  private long end;

  public ExecutionTimer() {
    reset();
    start = System.currentTimeMillis();
  }

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

  public long duration(){
    return (end-start);
  }

  public void reset() {
    start = 0;  
    end   = 0;
  }

  public static void main(String s[]) {
    // simple example
    ExecutionTimer t = new ExecutionTimer();
    for (int i = 0; i < 80; i++){
System.out.print(".");
}
    t.end();
    System.out.println("\n" + t.duration() + " ms");
  }
}