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

时间:2021-01-01 16:09:45

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.

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

10 个解决方案

#1


80  

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

#2


40  

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

#3


9  

Use a profiler.

使用分析器。

#4


8  

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

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

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

#5


6  

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。

#6


5  

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.mangement package.

一般来说,我建议围绕java.lang.mangement包。

#7


3  

System.nanoTime should 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.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.

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

#8


3  

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

#9


0  

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

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

#10


-2  

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

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

#1


80  

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

#2


40  

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

#3


9  

Use a profiler.

使用分析器。

#4


8  

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

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

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

#5


6  

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。

#6


5  

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.mangement package.

一般来说,我建议围绕java.lang.mangement包。

#7


3  

System.nanoTime should 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.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.

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

#8


3  

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

#9


0  

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

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

#10


-2  

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

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