java重复执行方法_测量Java方法的执行时间[重复]

问题

这个问题在这里已有答案:

如何计算方法在Java中的执行时间? 36个答案

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

#1 热门回答(192 赞)

你可以在之前和之后拍摄时间戳快照,然后重复几次实验以平均到结果.还有一些分析器可以为你执行此操作。

##来自"Java平台性能:策略与策略"一书:

使用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()和stop。

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

}

}

Seehere。

NetBeans Profiler:

应用程序性能应用程序性能配置文件方法级CPU性能(执行时间)。你可以选择分析整个应用程序或应用程序的一部分。

Seehere。

#2 热门回答(181 赞)

更确切地说,我会使用13250105方法而不是currentTimeMillis():

long startTime = System.nanoTime();

myCall();

long stopTime = System.nanoTime();

System.out.println(stopTime - startTime);

在Java 8中(输出格式为ISO-8601):

Instant start = Instant.now();

Thread.sleep(63553);

Instant end = Instant.now();

System.out.println(Duration.between(start, end)); // prints PT1M3.553S

Stopwatch stopwatch = Stopwatch.createStarted();

myCall();

stopwatch.stop(); // optional

System.out.println("Time elapsed for myCall() is "+ stopwatch.elapsed(MILLISECONDS));

#3 热门回答(32 赞)

有了这个,你可以通过以下方式计算方法的时间:

long start = System.currentTimeMillis();

class.method();

long time = System.currentTimeMillis() - start;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值