title: Preventing compiler optimizations while benchmarking
body: <p>I recently came across this brilliant cpp2015 talk <a href="https://www.youtube.com/watch?v=nXaxk27zwlk" rel="noreferrer">CppCon 2015: Chandler Carruth "Tuning C++: Benchmarks, and CPUs, and Compilers! Oh My!"</a></p>
  
  <p>One of the techniques mentioned to prevent the compiler from optimizing code is using the below functions. </p>
  
  <pre><code>static void escape(void *p) {
    asm volatile("" : : "g"(p) : "memory");
  }
  
  static void clobber() {
    asm volatile("" : : : "memory");
  }
  
  void benchmark()
  {
    vector&lt;int&gt; v;
    v.reserve(1);
    escape(v.data());
    v.push_back(10);
    clobber()
  }
  </code></pre>
  
  <p>I'm trying to understand this. Questions as follows.</p>
  
  <p>1) What is the advantage of an escape over clobber ?</p>
  
  <p>2) From the example above it looks like clobber() prevents the previous statement ( push_back ) to be optimized way. If that's the case why the below snippet is not correct ?</p>
  
  <pre><code> void benchmark()
   {
       vector&lt;int&gt; v;
       v.reserve(1);
       v.push_back(10);
       clobber()
   }
  </code></pre>
  
  <p>If this wasn't confusing enough, folly ( FB's threading lib ) has an even <a href="https://github.com/facebook/folly/blob/master/folly/Benchmark.h" rel="noreferrer">stranger implementation</a> </p>
  
  <p>Relevant snippet:</p>
  
  <pre><code>template &lt;class T&gt;
  void doNotOptimizeAway(T&amp;&amp; datum) {
    asm volatile("" : "+r" (datum));
  }
  </code></pre>
  
  <p>My understanding is that the above snippet informs the compiler that the assembly block will writes to datum. But if the compiler finds there is no consumer of this datum it can still optimize out the entity producing datum right ?</p>
  
  <p>I assume this is not common knowledge and any help is appreciated !</p>