This is my benchmark code sample :
Two ways of doing it :
volatile result = compute();
2nd way of doing it :
bool result = compute();
DoNotOptimize(result);
So i want to prevent the compiler to remove the compute() so which ones better ? Is it true that both have same effects ?
You should use
DoNotOptimize. Here is the example whenvolatiledoes not prevent variable optimization out: https://quick-bench.com/q/tvsxD71u3d_PLgA9IKx7jwA6CLs.The app is a single-threaded. The compiler knows
volatile std::string created_stringis never read.DoNotOptimizeforcly materializesstd::string created_string, promising to the compiler later use of the variable. For details look at this perfect answer: https://stackoverflow.com/a/69288151/6752050.