I am creating a little program measure the performance difference between containers of types boost::shared_ptr
and boost::intrusive_ptr
. In order to prevent the compiler from optimizing away the copy I declare the variable as volatile. The loop looks like this:
// TestCopy measures the time required to create n copies of the given container.
// Returns time in milliseconds.
template<class Container>
time_t TestCopy(const Container & inContainer, std::size_t n) {
Poco::Stopwatch stopwatch;
stopwatch.start();
for (std::size_t idx = 0; idx < n; ++idx)
{
volatile Container copy = inContainer; // Volatile!
}
// convert microseconds to milliseconds
return static_cast<time_t>(0.5 + (double(stopwatch.elapsed()) / 1000.0));
}
The rest of the code can be found here: main.cpp.
- Will using volatile here prevent the compiler from optimizing away the copy?
- Are there any pitfalls that may invalidate the results?
Update
In response to @Neil Butterworth. Even when using the copy it still seems to me that the compiler could easily avoid the copy:
for (std::size_t idx = 0; idx < n; ++idx)
{
// gcc won't remove this copy?
Container copy = inContainer;
gNumCopies += copy.size();
}
-O0
you can just guess the performance impact instead. The result similarly has no bearing on a realistic scenario. – Osugig++ -O4
, the copy constructor is called once per loop. (Aside: Yes, if theContainer
in question has a copy-constructor with no side-effects it can be optimized away, per 1.9/1 and 1.9/6. But, I'm asking about a copy constructor with side effects.) – Malcom