C++如何实现非常快速的操作

Mar*_*les 2 c++ floating-point benchmarking c++-chrono

我在VC++ 2013,Windows 7-64,Intel i7 3.6 GHz.我想测量非常快速的数学运算的执行时间,例如我希望将标准fabsf()函数的性能与替代的"更快"方法或标准tanh()与Pade近似等进行比较.

问题是这些操作太快了,即使我运行它们数十万次,我总是在基准测试的结束和开始之间获得0毫秒.

我试着用纳秒来获得时间,<chrono>但是它被四舍五入到十分之一毫秒,而不是真正的纳秒,所以在我的基准测试中我仍然得到0纳秒.

你能提供一些代码片段,我可以用它来运行我的基准测试吗?

这是我的:

#include <vector>
#include <chrono>
#include <ctime> 
using namespace std;

// 1/RAND_MAX
#define RAND_MAX_RECIP      0.00003051757f

int _tmain(int argc, _TCHAR* argv[])
{
    srand (static_cast <unsigned> (time(0)));

    // Fill a buffer with random float numbers
    vector<float> buffer;
    for (unsigned long i=0; i<10000000; ++i)
        buffer.push_back( (float)rand() * RAND_MAX_RECIP );

    // Get start time
    auto start = std::chrono::high_resolution_clock::now();

    for (unsigned long i=0; i<buffer.size(); ++i)
    {
        // do something with the float numbers in the buffer
    }

    // Get elapsed time
    auto finish = std::chrono::high_resolution_clock::now();

    printf("Executed in %d ns\n\n", std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count());

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Max*_*ert 6

我认为最可能的问题是编译器注意到您没有使用计算结果并优化计算.你只需要说服编译器不这样做.

我建议只保留所有计算结果的运行总和,并在打印循环所需的时间后打印出来.你会忽略最后的总和,但编译器不会知道.


Sin*_*per 5

为了防止Jens提到的问题,您必须使用结果.为了解决无论我设置计数器多少次的问题,时间总是0,你采取另一种方法.运行该操作1秒钟并计算处理的次数.

Psuedo代码是

   double TestFunc()
   {  
        double dSum=0, dForce=0;
        while(run)
        {
             // do test and keep the result
             // dForce += fabs(v); // whatever v is - just keep the result
             dSum +=1;  
        }
        printf("anchor answer is "+dForce) ;// this forces the compiler to generate code
        return dSum;
    }
Run Code Online (Sandbox Code Playgroud)

然后运行该代码1秒钟,或者多长时间.

然后诀窍是在没有测试代码的情况下运行相同的循环,并查看它迭代的次数.然后从第二个数字中减去第一个数字,看看你的代码(单独)花了多长时间.