测量Java方法的执行时间 [英] Measure execution time for a Java method

查看:608
本文介绍了测量Java方法的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算在Java中执行方法所需的时间?

How do I calculate the time taken for the execution of a method in Java?

推荐答案

您可以在之前拍摄时间戳快照之后,然后重复几次实验以平均结果。还有一些可以为您完成此操作的分析器。

You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.

使用System.currentTimeMillis()

class TimeTest1 {
   public static void main(String[] args) {

      long startTime = System.currentTimeMillis();

      long total = 0;
      for (int i = 0; i < 10000000; i++) {
         total += i;
      }

      long stopTime = System.currentTimeMillis();
      long elapsedTime = stopTime - startTime;
      System.out.println(elapsedTime);
   }
}

使用StopWatch类

您可以使用此 StopWatch 类,并调用 start()在方法之前和之后停止

You can use this StopWatch class, and call start() and stop before and after the method.

class TimeTest2 {
   public static void main(String[] args) {

      Stopwatch timer = new Stopwatch().start();

      long total = 0;
      for (int i = 0; i < 10000000; i++) {
         total += i;
      }

      timer.stop();
      System.out.println(timer.getElapsedTime());
   }
}

参见这里


应用程序性能应用程序

性能配置文件方法级CPU
性能(执行时间)
。你可以
选择描述整个
申请或
申请的一部分。

Performance profiles method-level CPU performance (execution time). You can choose to profile the entire application or a part of the application.

请参见此处

这篇关于测量Java方法的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆