在运行一些基准程序时,挂钟可能会意外地给出很小的持续时间,这是由于各种编译器优化,如死区代码消除、循环展开。。。优化了测试代码。
我可以通过static/volatile限定符添加一些“外部依赖性”,但这并不总是有效的。
知道吗?
最佳答案
通常,通过static/volatile限定符添加“一些”外部依赖“将改变实际行为,因此不建议计时。
我通常通过使用argc
(main的第一个参数)来确保代码可以被测试
如果需要循环,则使用argc
更改输入数据。还有一些虚拟的计算值,它依赖于代码,并在循环和计时器之后打印,以确保结果不能优化。
如果fill函数可以接受种子,也可以将argc
用作种子的一部分。
因此,如果您有随机测试数据,或者有一个用于测试代码的循环,请将argc
添加到其中。
不知道你在测试什么我能做的就是
seed=argc; // the compiler cannot count on any value of argc
dummy=0;
total_time=0;
for (rep=0; rep < max_rep; ++rep)
{
for (i =0; i < max_array; ++i)
{
test_array[i]=seed+gen_random(); // Note use of seed
}
start=time_now();
dummy+=function_to_time(test_array); // this is what you are testing
end=time_now();
total_time+=end-start;
seed++; // change seed just to be extra paranoid
}
std::cout << "Time=" << total_time << " Dummy=" << dummy << std::endl;
关于c++ - 如何在 Release模式下正确编写基准测试程序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21094632/