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

发布于 2024-07-15 20:31:22 字数 110 浏览 4 评论 0 原文

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

注意:

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

打小就很酷 2024-07-22 20:31:22
long start = System.nanoTime();    
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;
long start = System.nanoTime();    
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;
且行且努力 2024-07-22 20:31:22

以下是如何计算经过的时间。

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

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);
债姬 2024-07-22 20:31:22

如果您使用的是 Guava,请考虑使用 秒表,例如:

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

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

final Stopwatch sw = Stopwatch.createStarted();
methodToBeTimed();
final long elapsedMillis = sw.elapsed(TimeUnit.MILLISECONDS);
ら栖息 2024-07-22 20:31:22

如果您有多个函数,则探查器是正确的答案。

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

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

看看 AspectJ 或 Spring 的 AOP。

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.

Have a look at AspectJ or Spring's AOP.

海夕 2024-07-22 20:31:22

上面的所有代码片段都测量从调用方法到方法返回/抛出异常所花费的大致时间。 这些技术不解决线程调度、GC 引起的暂停等问题。

是的,一些分析器会完成合理的工作。

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

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

如果您的方法产生工作线程,那么您的计算将需要变得更加复杂;-)

一般来说,我建议仔细研究 java.lang.mangement 包。

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.

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:

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

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.

唐婉 2024-07-22 20:31:22

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 返回当前时间(以毫秒为单位)。 您可以使用它来获取当前时间。 这对于较旧的虚拟机或运行时间较长的进程可能很有用。

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.

弥繁 2024-07-22 20:31:22

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

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

int someMethod() {
    long tm = System.nanoTime();
    try {
        ...
    } finally {
        tm = System.nanoTime()-tm;
        System.out.println("time spent in someMethod(): " + tm + "ns");
    }
}
想挽留 2024-07-22 20:31:22

这个模拟秒表也是我们的另一个选择......
请访问Java2s.com

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文