Just a beginner question.
In the code from cppreference.com, there is a comment saying, "make sure it's a side effect" on the line using std::accumulate
.
What is the author's intention in saying this? Is it related to the
volatile int sink
? (Maybe it means something like "make sure thesink
is not optimized by the compiler"?)Why
volatile
forsink
? I think almost every compiler might know thestd::accumulate
will change the value ofsink
.
I thought I knew what volatile
and "side-effect" meant, but maybe I'm missing some point!
#include <iostream>
#include <iomanip>
#include <vector>
#include <numeric>
#include <chrono>
volatile int sink;
int main()
{
std::cout << std::fixed << std::setprecision(9) << std::left;
for (auto size = 1ull; size < 1000'000'000ull; size *= 100) {
// record start time
auto start = std::chrono::system_clock::now();
// do some work
std::vector<int> v(size, 42);
// This is the line I mentioned.
sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect
// record end time
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "Time to fill and iterate a vector of " << std::setw(9)
<< size << " ints : " << diff.count() << " s\n";
}
}