Using volatile to prevent compiler optimization in benchmarking code?
<p>I am creating a little program measure the performance difference between containers of types <code>boost::shared_ptr</code> and <code>boost::intrusive_ptr</code>. In order to prevent the compiler from optimizing away the copy I declare the variable as volatile. The loop looks like this:</p>

<pre><code>// TestCopy measures the time required to create n copies of the given container.
// Returns time in milliseconds.
template&lt;class Container&gt;
time_t TestCopy(const Container &amp; inContainer, std::size_t n) {
    Poco::Stopwatch stopwatch;
    stopwatch.start();
    for (std::size_t idx = 0; idx &lt; n; ++idx)
    {
        volatile Container copy = inContainer; // Volatile!
    }

    // convert microseconds to milliseconds
    return static_cast&lt;time_t&gt;(0.5 + (double(stopwatch.elapsed()) / 1000.0));
}
</code></pre>

<p>The rest of the code can be found here: <a href="http://code.google.com/p/stacked-crooked/source/browse/trunk/PlayGroundCpp/RefcountPerformance/main.cpp" rel="nofollow">main.cpp</a>.</p>

<ul>
<li>Will using volatile here prevent the compiler from optimizing away the copy?</li>
<li>Are there any pitfalls that may invalidate the results?</li>
</ul>

<h3>Update</h3>

<p>In response to @Neil Butterworth. Even when using the copy it still seems to me that the compiler could easily avoid the copy:</p>

<pre><code>for (std::size_t idx = 0; idx &lt; n; ++idx)
{
    // gcc won't remove this copy?
    Container copy = inContainer;
    gNumCopies += copy.size();        
}
</code></pre>
