简体   繁体   English

测量功能执行时间

[英]Measuring time for the execution of functions

I am stuck at measuring execution time for the functions in C++.我一直在测量 C++ 中函数的执行时间。 I tried clock_t clock(void) but it measures just the time for the one function in the program.我尝试了clock_t clock(void)但它只测量程序中一个函数的时间。 In the below simple example how can i measure time for the two functions?在下面的简单示例中,我如何测量这两个函数的时间?

#include <iostream>

using namespace std;

int add(int a, int b)
{
    return a+b;
}

int subtract(int a, int b)
{
    return a - b;
}

int main()
{
    int a,b;
    cin >> a >> b;

    int c = add(a,b);
    int d = subtract(a,b);
    cout << c << " " << d << "\n";
    return 0;
}

If you want to do benchmarking, instead of using std::clock_t you should consider using time_point<high_resolution_clock> using std::chrono :如果你想做基准测试,而不是使用std::clock_t你应该考虑使用time_point<high_resolution_clock>使用std::chrono time_point<high_resolution_clock>

    using namespace std::chrono; 

    high_resolution_clock::time_point t = high_resolution_clock::now();
    //... do what is to be measured
    high_resolution_clock::time_point t2 = high_resolution_clock::now();
    cout << duration_cast<milliseconds>(t2 - t).count();

However, timing is always an imprecise measure that depends on the clock resolution (on windows for example, the resolution is around 15 ms).但是,时序始终是一种不精确的度量,它取决于时钟分辨率(例如,在 Windows 上,分辨率约为 15 ms)。 So the shorter the time you measure, the higher is the relative error in the measure.所以你测量的时间越短,测量的相对误差就越大。 So if your function takes 15 ms to execute, on windows, you'll have an error in the measure of +/- 100%.因此,如果您的函数执行时间为 15 毫秒,则在 Windows 上,您将有 +/- 100% 的误差。

The only way you can increase reliability of the measure, is to measure a longer time, by having a huge number of iterations.提高测量可靠性的唯一方法是通过大量迭代来测量更长的时间。 So in the example, with 1 million iterations, the relative error of the measure is 0,0001%.因此,在示例中,经过 100 万次迭代,度量的相对误差为 0,0001%。

If you can benchmark your functions separately, just do it like that.如果您可以单独对您的功能进行基准测试,那么就这样做。 But if you can't measure your functions separately (for example because one produces the input for the other), you can't use this approach).但是如果你不能单独测量你的函数(例如因为一个函数为另一个函数产生输入),你就不能使用这种方法)。 If you want to find the bottleneck your code in such case, then you should use the right tool: a profiler .如果您想在这种情况下找到代码的瓶颈,那么您应该使用正确的工具: 分析器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM