c++optimizationbenchmarkinggoogle-benchmark

DoNotOptimize from google benchmark vs volatile keyword for optimising out


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 ?


Solution

  • You should use DoNotOptimize. Here is the example when volatile does 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_string is never read.

    DoNotOptimize forcly materializes std::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.