Is there a standard way to prevent code reordering when profiling functions in c++? Let's say I have a code like this
void foo() {
const auto timeStart = std::chrono::system_clock::now();
// code that we want to profile.....
const auto timeEnd = std::chrono::system_clock::now();
std::cout << "Took " << (timeEnd - timeStart).count() << "\n";
}
Compiler is free to reorder the instructions if there is no side effect. In this case timeStart does not get used till the very end. Can compiler rearrange the function to something like -
void foo() {
// code that we want to profile.....
const auto timeStart = std::chrono::system_clock::now();
const auto timeEnd = std::chrono::system_clock::now();
std::cout << "Took " << (timeEnd - timeStart).count() << "\n";
}
If yes, then how to prevent the reordering of instructions around timeStart, or timeEnd? Is using full memory barrier the only option? Where exactly do we need to insert the barrier- do we insert the barrier before and after the timestart and before and after the timeEnd?
Thanks