如何计算在 Java 中完成一个函数所需的时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/692569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:25:17  来源:igfitidea点击:

How can I count the time it takes a function to complete in Java?

javaprofiling

提问by fmsf

I need to measure the time it takes for a function to complete in Java. How can I do that?

我需要测量一个函数在 Java 中完成所需的时间。我怎样才能做到这一点?

Note:

笔记:

I want to measure the function's time consumption, not that of the full program.

我想测量函数的时间消耗,而不是完整程序的时间消耗。

采纳答案by Ande Turner

long start = System.nanoTime();    
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;

回答by Jakub Arnold

If you want to get current time, use java.util.Date.

如果要获取当前时间,请使用java.util.Date.

回答by McDowell

System.nanoTimeshould be used to accurately measure the delta between two times for microbenchmarks.

System.nanoTime应用于准确测量微基准测试两次之间的增量。

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.currentTimeMillisreturns 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.

System.currentTimeMillis以毫秒为单位返回当前时间。您可以使用它来获取当前时间。这可能对较旧的 VM 或运行时间较长的进程有用。

回答by Maurice Perry

Use either System.currentTimeMillis() or System.nanoTime():

使用 System.currentTimeMillis() 或 System.nanoTime():

int someMethod() {
    long tm = System.nanoTime();
    try {
        ...
    } finally {
        tm = System.nanoTime()-tm;
        System.out.println("time spent in someMethod(): " + tm + "ns");
    }
}

回答by Christian Stade-Schuldt

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

回答by Aaron Maenpaa

回答by duffymo

The profiler is the right answer if you have more than one function.

如果您有多个功能,探查器是正确的答案。

Another problem that I see with all the suggestions given so far is that they work fine for a single function, but your code will be littered with timing stuff that you can't turn off.

到目前为止,我看到的所有建议的另一个问题是它们对单个函数工作正常,但是您的代码将充斥着无法关闭的计时内容。

If you know how to do aspect oriented programming, it's a good way to keep the timing code in one place and apply it declaratively. If you use something like Log4J to output the values, you'll have the option of turning it off or on. It's a poor man's profiler.

如果您知道如何进行面向方面的编程,那么将计时代码保存在一个地方并以声明方式应用它是一种很好的方法。如果您使用 Log4J 之类的东西来输出值,您可以选择关闭或打开它。这是一个穷人的侧写器。

Have a look at AspectJ or Spring's AOP.

看看 AspectJ 或 Spring 的 AOP。

回答by Dilum Ranatunga

All of the code snippets above measure the approximate time elapsed from the time the method was invoked to the time the method returns/throws an exception. Such techniques do not address thread scheduling, pauses due the GC, etc.

上面的所有代码片段都测量了从调用方法到方法返回/抛出异常的大致时间。此类技术不解决线程调度、由于 GC 导致的暂停等问题。

Yes, some profilers will do a reasonable job.

是的,一些分析器会做一个合理的工作。

If you are using Java 1.6 onwards, you can use the JMX based VM management and monitoring support. For example, you may find ThreadMXBean.getCurrentThreadCpuTime()of value. Calculating the difference of this value before and after the method invoke will give you:

如果您使用的是 Java 1.6 及更高版本,则可以使用基于 JMX 的 VM 管理和监控支持。例如,您可能会发现ThreadMXBean.getCurrentThreadCpuTime()的值。计算方法调用前后此值的差异将为您提供:

"... the total CPU time for the current thread in nanoseconds. The returned value is of nanoseconds precision but not necessarily nanoseconds accuracy. If the implementation distinguishes between user mode time and system mode time, the returned CPU time is the amount of time that the current thread has executed in user mode or system mode."

"...当前线程的总CPU时间,以纳秒为单位。返回值是纳秒精度,但不一定是纳秒精度。如果实现区分用户模式时间和系统模式时间,则返回的CPU时间是时间量当前线程已在用户模式或系统模式下执行。”

If your method spawns off worker threads, then your computation will need to get far more elaborate ;-)

如果您的方法从工作线程中产生,那么您的计算将需要更加精细;-)

In general, I recommend nosing around the java.lang.mangementpackage.

一般来说,我建议在java.lang.mangement包周围寻找。

回答by gumuruh

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

这个模拟秒表也是我们的另一种选择......在这里查看Java2s.com。

回答by Jonathan

If you are using Guava, consider using the Stopwatch, e.g.:

如果您使用的是番石榴,请考虑使用Stopwatch,例如:

final Stopwatch sw = Stopwatch.createStarted();
methodToBeTimed();
final long elapsedMillis = sw.elapsed(TimeUnit.MILLISECONDS);