2

How to measure the time cost of running a Java program? How to estimate the time cost of my program. (The program is running in eclipse)

Code:

import java.util.Scanner;

public class S1_4 {

public static void main(String[] args) {
    int i,j,k=1;
    int[] table = new int[1000001];
    for(i = 2;i<1000000;i++)
     {
      if(table[i]==0)
         {
         for(j=1;i*j<999999;j++)
            table[i*j]=k;
            k++;
         }
     }

    int a;
    Scanner cin = new Scanner(System.in);

    while(cin.hasNext()) {
        a = cin.nextInt();          
        System.out.println(table[a]);
    }
    cin.close();
}

}
Knight Shao
  • 89
  • 2
  • 8
  • 1
    Have you seen: http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java ? – harpun Apr 15 '13 at 06:08
  • Actually there is a AOP(aspectj, for instance) approach if you do not want to change the existing code. – Hongxu Chen Apr 15 '13 at 06:15

3 Answers3

6

Use System.nanoTime() instead of System.currentTimeMillis(),because currentTimeMillis() depends on system clock,but nanoTime() returns a reletive time,not depends on system clocks.

if your system clock changed between the two invoke of currentTimeMillis(),the time interval is meanless.

long start = System.nanoTime();
    //time consuming code here.
    //...
    long end = System.nanoTime();
    long used = end-start;
    System.out.println("used:"+TimeUnit.NANOSECONDS.toMillis(used)+" ms");

See here for details.

BlackJoker
  • 3,099
  • 2
  • 20
  • 27
1
public static void main(String[] args) {
  long startTime = System.currentTimeMillis();
  ...
  System.out.println("Time taken-"+(System.currentTimeMillis() -startTime));
}
Jaydeep Rajput
  • 3,605
  • 17
  • 35
0

measuring time it takes to run a method is harder if method takes very little time. The nano counter is not stable enough. I'd suggest running the method a lot of times and measure the combined running time. That will also allow the JIT compiler to optimize it so you know how much would it take actually at runtime.

You can use jmeter or other perf testing framework or you can write your own loop to execute the code many times. The other two answers give you good pointers how to measure time a code takes. I'm recommending you to measure time a great number of runs (e.g. 10k) instead of only one run.

akostadinov
  • 17,364
  • 6
  • 77
  • 85