【发布时间】:2020-02-14 18:54:25
【问题描述】:
这是关于钱德勒的回答的问题(我没有足够高的代表发表评论):Enforcing statement order in C++
在他的回答中,假设 foo() 没有输入或输出。这是一个黑匣子,最终可以观察到,但不会立即需要(例如执行一些回调)。所以我们没有本地的输入/输出数据来告诉编译器不要优化。但我知道 foo() 会在某处修改内存,结果最终会被观察到。在这种情况下,以下内容会阻止语句重新排序并获得正确的时间吗?
#include <chrono>
#include <iostream>
//I believe this tells the compiler that all memory everywhere will be clobbered?
//(from his cppcon talk: https://youtu.be/nXaxk27zwlk?t=2441)
__attribute__((always_inline)) inline void DoNotOptimize() {
asm volatile("" : : : "memory");
}
// The compiler has full knowledge of the implementation.
static int ugly_global = 1; //we print this to screen sometime later
static void foo(void) { ugly_global *= 2; }
auto time_foo() {
using Clock = std::chrono::high_resolution_clock;
auto t1 = Clock::now(); // Statement 1
DoNotOptimize();
foo(); // Statement 2
DoNotOptimize();
auto t2 = Clock::now(); // Statement 3
return t2 - t1;
}
【问题讨论】:
-
你不想要std::memory_order而不是编译器特定的黑客吗?
-
写入内存是副作用,因此如果
foo在某处修改内存,则编译器无法重新排序时钟调用。否则就不可能编写程序并让它们做你想做的事情。 -
@JesperJuhl 我不知道如何在这里使用 std::memory_order ...我没有使用内存中的特定位置(在黑盒之外已知)。也许我只是对他们不熟悉。
-
@P.Mattione 老实说,我也不知道。当我看到你的问题时,这只是我脑海中闪现的第一件事。所以我很可能完全跑题了/错了。
-
@MooingDuck:请在您的评论中添加@以获取通知 :-) 并且如前所述:硬件本身可以重新排序执行,这是编译器无法控制的,只要没有特殊说明发出停止这些重新排序!另请参阅:stackoverflow.com/questions/27471969/…。 memory_order 也没有阻止任何事情,因为可以重新排序没有副作用的耗时的事情
标签: c++ optimization memory time compiler-construction