我正在创建一个小程序,用于测量类型为boost::shared_ptr
和boost::intrusive_ptr
的容器之间性能差异。为了防止编译器优化掉复制操作,我将变量声明为volatile。循环如下:
// 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));
}
代码的其余部分可以在这里找到:main.cpp。
- 在这里使用volatile关键字是否会防止编译器优化掉复制操作?
- 有哪些可能会使结果无效的陷阱?
更新
回应@Neil Butterworth。即使使用了复制,我仍然认为编译器很容易避免复制:
for (std::size_t idx = 0; idx < n; ++idx)
{
// gcc won't remove this copy?
Container copy = inContainer;
gNumCopies += copy.size();
}