I want to measure the time a function I programmed takes when executed. While there are many threads on SO on how to measure time in c++, I did not find any that explains how to prevent the compiler optimization to clear away my function-call. So right now I do something like:
bool testFunctionSpeed() {
auto input = loadInput();
auto start = std::chrono::high_resolution_clock::now();
for (int i; i < num_iterations; i++) {
auto result = function(input);
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
}
It appears to work right now, but I'm not sure if this is stable, because: Doing this, the compiler can see that the result stored in "result" is not used outside of the loop's scope, so it might just optimize the code away (...right?).
I am aware that there are flags to not optimize the code, however I want to benchmark my code under "real" conditions! One way would be to randomly printf out parts of the result, however that does not seem to be a "correct" solution.
What is the right approach to this?