Knight Shao
Knight Shao

Reputation: 89

How to measure the time cost?

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

}

Upvotes: 2

Views: 3469

Answers (3)

akostadinov
akostadinov

Reputation: 18594

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.

Upvotes: 0

BlackJoker
BlackJoker

Reputation: 3191

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.

Upvotes: 6

Jaydeep Rajput
Jaydeep Rajput

Reputation: 3673

public static void main(String[] args) {
  long startTime = System.currentTimeMillis();
  ...
  System.out.println("Time taken-"+(System.currentTimeMillis() -startTime));
}

Upvotes: 1

Related Questions