1

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 ?

hft654
  • 51
  • 6
  • https://stackoverflow.com/questions/66795357/google-benchmark-frameworks-donotoptimize – Alan Birtles Aug 06 '23 at 06:40
  • Pretty similar except no store actually has to happen for `DoNotOptimize`, the compiler just needs to materialize the value in a register. (And it's a compiler memory barrier for *other* variables, at least ones where references have escaped the function.) IIRC, `DoNotOptimize` might use `"+r"` to make the compiler forget about the value of `result`, which is useful if you use it on a value that's used again later, not like the dead end use here. – Peter Cordes Aug 06 '23 at 06:56
  • thanks @PeterCordes ! I am a huge fan of you! if its okay with you can you please give me learning roadmap to the world of low latency development ? i am 18 year old working as an intern at an hft company. I want to increase my skill and value. i really love this field. advance thanks – hft654 Aug 06 '23 at 07:51

1 Answers1

4

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.

273K
  • 29,503
  • 10
  • 41
  • 64