C ++优化器将对clock()的调用重新排序是合法的吗? [英] Is it legal for a C++ optimizer to reorder calls to clock()?

查看:137
本文介绍了C ++优化器将对clock()的调用重新排序是合法的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++程式设计语言 第四版第225页内容如下: em>编译器可以重新排序代码以提高性能,只要结果与简单执行顺序相同即可。一些编译器,例如。 Visual C ++在发布模式下,将重新排序此代码:

The C++ Programming Language 4th edition, page 225 reads: A compiler may reorder code to improve performance as long as the result is identical to that of the simple order of execution. Some compilers, e.g. Visual C++ in release mode, will reorder this code:

#include <time.h>
...
auto t0 = clock();
auto r  = veryLongComputation();
auto t1 = clock();

std::cout << r << "  time: " << t1-t0 << endl;

添加到此表单中:

auto t0 = clock();
auto t1 = clock();
auto r  = veryLongComputation();

std::cout << r << "  time: " << t1-t0 << endl;

这将确保与原始代码不同的结果(零与大于零的时间报告)。有关详细示例,请参见我的其他问题。这个行为是否符合C ++标准?

which guarantees different result than original code (zero vs. greater than zero time reported). See my other question for detailed example. Is this behavior compliant with the C++ standard?

推荐答案

编译器不能交换两个 clock 呼叫。必须在 t0 后设置 t1 。两种调用都是可观察到的副作用。编译器可以在这些可观察效应之间重新排序任何事物,甚至在可观察到的副作用之外,只要观察结果与抽象机器的可能观察一致即可。

The compiler cannot exchange the two clock calls. t1 must be set after t0. Both calls are observable side effects. The compiler may reorder anything between those observable effects, and even over an observable side effect, as long as the observations are consistent with possible observations of an abstract machine.

由于C ++抽象机不是正式限于有限速度,它可以在零时间执行 veryLongComputation() 。执行时间本身不定义为可观察效应。实际的实现可能匹配。

Since the C++ abstract machine is not formally restricted to finite speeds, it could execute veryLongComputation() in zero time. Execution time itself is not defined as an observable effect. Real implementations may match that.

请注意,这很大一部分答案取决于C ++标准不是对编译器施加限制。

Mind you, a lot of this answer depends on the C++ standard not imposing restrictions on compilers.

这篇关于C ++优化器将对clock()的调用重新排序是合法的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆