I want to profile a certain function and in order to get more reliable results I call the function in a loop. I was concerned that the compiler would see that I never use the result and optimize away my loop, so I thought I could just copy the result to a variable marked as volatile to prevent that (demo here).
#include <chrono>
struct Bar{};
Bar foo();
Bar profile_foo()
{
// result is marked volatile so the loop isn't optimized away
volatile Bar result;
for(int i = 0; i< 10000; i++)
result = foo();
return result;
}
int main(int argc, char* argv[])
{
using namespace std::chrono;
auto begin = high_resolution_clock::now();
auto result = profile_foo();
auto end = high_resolution_clock::now();
auto time_passed = duration_cast<milliseconds>(end-begin).count();
// validate result ...
}
Turns out there is no default copy constructor/assignment operator between a volatile/non-volatile instance of a class. See this post.
So,
- is there any other way to assign a non-volatile to a volatile and vice versa? Or,
- is there another way to tell the compiler not to optimize away the loop?
Note: I cannot modify the class Bar.