Preventing the Compiler from Optimizing Away Benchmarks

jmh530 john.michael.hall at gmail.com
Mon Mar 13 14:17:57 UTC 2023


I was looking at [1] for ways to prevent the compiler from 
optimizing away code when trying to benchmark.

It has the following C++ code as a simpler version:
```
inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) {
     asm volatile("" : "+r,m"(value) : : "memory");
}
```

I made an attempt to make a D version of it, but failed. 
Apparently DMD doesn't like the `""` in the first part of the asm 
instruction. I'm also not sure the `volatileLoad` command is 
right, but I didn't know of any other way to have volatile work 
in D (and I couldn't figure out how it actually worked from 
looking at the code).

```
void DoNotOptimize(T)(T* ptr)
{
     import core.volatile: volatileLoad;
     T value = volatileLoad(ptr);
     asm {"" : "+r,m"(value) : : "memory";}
}
```

[1] 
https://theunixzoo.co.uk/blog/2021-10-14-preventing-optimisations.html


More information about the Digitalmars-d-learn mailing list