测试C ++应用程序的性能 [英] Testing the performance of a C++ app

查看:162
本文介绍了测试C ++应用程序的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法来测试一段C ++代码运行需要多长时间。我使用它来比较代码与不同的算法和不同的语言,所以理想情况下,我想要一个时间在几秒/毫秒。在Java中我使用这样的:

I'm trying to find a way to test how long it takes a block of C++ code to run. I'm using it to compare the code with different algorithms and under different languages, so ideally I would like a time in seconds / milliseconds. In Java I'm using something like this:

long startTime = System.currentTimeMillis();

function();

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

有一个很好的方法来获得像C ++中那样准确的时间

Is there a good way to get an accurate time like that in C++ (Or should I use some other means of benchmarking)?

使用您的平台上可用的最佳计数器,回到时间(),以实现可移植性。)

解决方案

推荐答案

一般建议:

内部循环应至少运行时钟的分辨率的20倍,以使分辨率误差< 5%。 (因此,当使用time()时,内部循环至少应该运行20秒)

The inner loop should run at least about 20 times the resolution of your clock, to make the resolution error < 5%. (so, when using time() your inner loop should run at least 20 seconds)

重复这些测量,看看它们是否一致。

Repeat these measurements, to see if they are consistent.

我使用额外的外层循环,运行十次,忽略计算平均值和偏差的最快和最慢的测量。偏差在比较两个实现时很方便:如果你有一个算法采用2.0ms +/-。5,另一个2.2 +/- .5,差别不显着,调用其中一个更快。
(仍然应该显示最大值和最小值)。所以IMHO的有效性能测量应该看起来像这样:

I use an additional outer loop, running ten times, and ignoring the fastest and the slowest measurement for calculating average and deviation. Deviation comes handy when comparing two implementations: if you have one algorithm taking 2.0ms +/-.5, and the other 2.2 +/- .5, the difference is not significant to call one of them "faster". (max and min should still be displayed). So IMHO a valid performance measurement should look something like this:

10000 x 2.0 +/- 0.2 ms (min = 1.2, , max=12.6), 10 repetitions



如果你知道你在做什么,清除缓存和设置线程亲和力可以使您的测量更加强大。

If you know what you are doing, purging the cache and setting thread affinity can make your measurements much more robust.

但是,这不是没有pifalls。测量越稳定,也越不现实。任何实现将随时间变化很大,这取决于数据和指令高速缓存的状态。我在这里懒,使用max =值来判断第一次运行惩罚,这可能不足以在一些情况下。

However, this is not without pifalls. The more "stable" the measurement is, the less realistic it is as well. Any implementation will vary strongly with time, depending on the state of data and instruction cache. I'm lazy here, useing the max= value to judge first run penalty, this might not be sufficient for some scenarios.

这篇关于测试C ++应用程序的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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