How can I count the time it takes a function to co

2019-01-30 10:23发布

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.

10条回答
孤傲高冷的网名
2楼-- · 2019-01-30 11:16

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);
查看更多
做个烂人
4楼-- · 2019-01-30 11:18

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.

查看更多
Viruses.
5楼-- · 2019-01-30 11:21

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

查看更多
登录 后发表回答