考虑以下代码来衡量函数花费的时间:
// 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
并阻止优化。