I've been using, up until now, the traditional way to benchmark concurrent methods, which is to measure the elapsed duration for a number of runs:
template <typename Functor>
double benchmark(Functor const& f, size_t nbRuns)
{
if (nbRuns == 0) { return 0.0; }
f(); // Initialize before measuring, I am not interesting in setup cost
time_t begin = time(0);
for (size_t i = 0; i != nbRuns; ++i) { f(); }
time_t end = time(0);
return difftime(end, begin);
}
which seemed all fine and dandy until I came upon this question: Optimizing away a "while(1);" loop in C++0x.
What strikes me as unusual is that the compiler is allowed to execute the output BEFORE the loop... and I am suddenly wondering:
What prevents the compiler from executing
time_t end = time(0);
before the loop here ?
because if it did, that would somehow screw my little benchmark code.
And while we are at it, if ever the reordering could occur in this situation:
How can one prevent it ?
I could not think of relevant tags apart from the C++ ones, if anyone think I've missed one, feel free to add it