Let's say we have such a piece of c++ code:
auto t1 = getSystemTime(); // Statement 1
foo(); // Statement 2
auto t2 = getSystemTime(); // Statement 3
auto elapsedTime = t2 - t1;
As my understanding, the compiler may optimize the code, meaning that it may reorder the execution order only if it doesn't break the as-if rule. For example, the order of execution of the code below
c = a + b;
d = e + f;
can be reordered as
d = e + f;
c = a + b;
So, the piece of code above may be reordered as below:
auto t1 = getSystemTime(); // Statement 1
auto t2 = getSystemTime(); // Statement 3
foo(); // Statement 2
auto elapsedTime = t2 - t1;
which produces a totally different result.
After googling this issue, I got this: __asm__ __volatile__ ("" ::: "memory");
. If I'm right, with this line, we can disable the optimisation of the compiler so the execution order won't be reordered.
If I use it correctly, the code would become as below:
__asm__ __volatile__ ("" ::: "memory");
auto t1 = getSystemTime(); // Statement 1
foo(); // Statement 2
auto t2 = getSystemTime(); // Statement 3
auto elapsedTime = t2 - t1;
However, after reading some docs, I found that __asm__ __volatile__ ("" ::: "memory");
was just about compile-time, instead of runtime.
Now I'm confused. If __asm__ __volatile__ ("" ::: "memory");
works only during compile-time, does it mean that it is kind of totally useless because the execution order still can be changed at runtime? If so, is there some other mechanism to forbid the reordering at runtime? Or there is not any other mechanism so the execution order still can be reordered while runtime but with __asm__ __volatile__ ("" ::: "memory");
we can decrease the probability of reordering?
Besides, we have memory order in C++11, can the memory order help on this issue?
Aucun commentaire:
Enregistrer un commentaire