C++编程语言第4版,第225页读取:只要结果与简单执行顺序的结果相同,编译器就可以重新排序代码以提高性能.一些编译器,例如发布模式下的Visual C++,将重新排序此代码:
#include <time.h>
...
auto t0 = clock();
auto r = veryLongComputation();
auto t1 = clock();
std::cout << r << " time: " << t1-t0 << endl;
Run Code Online (Sandbox Code Playgroud)
进入这种形式:
auto t0 = clock();
auto t1 = clock();
auto r = veryLongComputation();
std::cout << r << " time: " << t1-t0 << endl;
Run Code Online (Sandbox Code Playgroud)
这保证了与原始代码不同的结果(零与大于零的时间报告).有关详细示例,请参阅我的其他问题 这种行为是否符合C++标准?