在运行一些基准程序时,挂钟可能会给出非常短的持续时间,这是因为各种编译器优化,如死代码消除、循环展开......优化了测试代码。
我可能会通过 static/volatile 限定符添加一些“外部依赖”,但这并不总是有效。
有什么想法吗?
通常,添加“通过静态/ volatile 限定符的一些‘外部依赖’”会改变实际行为,因此不建议在时机上这样做。
我通常确保代码可以测试的方法是使用 argc
(main 的第一个 arg)如果我需要循环,我会使用 argc
更改输入数据。还有一些虚拟计算值取决于代码并在循环和计时器之后打印,以确保结果不会被优化掉。
如果您的填充函数可以使用种子,您也可以只使用 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;
我是一名优秀的程序员,十分优秀!