Java中的CPU执行时间 [英] CPU execution time in Java

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

问题描述

我想计算我的函数在Java中执行需要多少CPU时间。目前我正在做如下。

I want to calculate how much CPU time my function takes to execute in Java. Currently I am doing as below.

   long startTime = System.currentTimeMillis();
    myfunction();
    long endTime = System.currentTimeMillis();
    long searchTime = endTime - startTime;

但我发现同一个I / PI会根据系统负载获得不同的时间。

But I found out that for the same I/P I get different time depending on system load.

那么,如何获得我的函数执行所需的精确CPU时间。

So, how to get exact CPU time my function took to execute.

推荐答案

随着JVM的升温,所用的时间会有所不同。第二次运行它总是比第一次快。 (第一次必须加载类并调用静态块)运行方法10,000次之后它会再次更快(将代码编译为本机机器代码的默认阈值)

As the JVM warms up the amount of time taken will vary. The second time you run this will always be faster than the first. (The first time it has to load classes and call static blocks) After you have run the method 10,000 times it will be faster again (The default threshold at which it compiles code to native machine code)

为了获得微基准的可重现平均时间,我建议你忽略前10,000次迭代并在此之后运行2-10秒。

To get a reproducable average timing for a micro-benchmark, I suggest you ignore the first 10,000 iterations and run it for 2-10 seconds after that.

例如

long start = 0;
int runs = 10000; // enough to run for 2-10 seconds.
for(int i=-10000;i<runs;i++) {
    if(i == 0) start = System.nanoTime();
    // do test
}
long time = System.nanoTime() - start;
System.out.printf("Each XXXXX took an average of %,d ns%n", time/runs);

非常重要:每种方法只能执行其中一个循环。这是因为它根据使用方式优化了整个方法。如果你有一个像这样的繁忙循环,后面的循环将显得较慢,因为它们没有运行并且将被很好地优化。

Very important: Only do one of these loops per method. This is because it optimises the whole method based on how it is used. If you have one busy loop like this the later loops will appear slower because they have not run and will be optimised poorly.

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

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