防止基准功能中的副作用优化

时间:2014-04-22 04:26:51

标签: c++ c++11 benchmarking compiler-optimization chrono

考虑以下代码来衡量函数花费的时间:

// Preprocessor
#include <iostream>
#include <chrono>

// Benchmarking function
template <class Function, class... Args>
double benchmark(Function&& f, Args&&... args)
{
    using clock = std::chrono::high_resolution_clock;
    using duration = std::chrono::duration<double>;
    auto tbegin = clock::now();
    std::forward<Function>(f)(std::forward<Args>(args)...);
    auto tend = clock::now();
    return std::chrono::duration_cast<duration>(tend-tbegin).count();
}

// Some example
unsigned int f(unsigned int n)
{
    unsigned int r = 0;
    for (unsigned int i = 0; i < n; ++i)
        for (unsigned int j = 0; j < n; ++j)
            r += (i*n)%(j+i+1);
    return r;
}

// Main function
int main()
{
    std::cout<<f(8192)<<std::endl; // Takes time
    std::cout<<benchmark(f, 8192)<<std::endl; // Takes no time
    return 0;
}

当函数f没有副作用时出现问题:编译器不执行它。有没有办法以通用方式修改我的benchmark函数,以强制执行f并阻止优化。

0 个答案:

没有答案
相关问题