Preventing the Compiler from Optimizing Away Benchmarks

jmh530 john.michael.hall at gmail.com
Mon Mar 13 16:14:54 UTC 2023


On Monday, 13 March 2023 at 15:23:25 UTC, user1234 wrote:
> [snip]
>>
>> [1] 
>> https://theunixzoo.co.uk/blog/2021-10-14-preventing-optimisations.html
>
> that's illegal code. You mix GCC/LLVM syntax with D asm block 
> and the front-end wont recognize that.
>
> LDC recognizes a syntax similar to what is described in your 
> link, see 
> https://wiki.dlang.org/LDC_inline_assembly_expressions. GDC has 
> it too (since that the syntax invented by GCC in first place)  
> but I cant find the documentation ATM.

Thanks, that helps. Below seems to be working...(with LDC and -O) 
when I include the DoNotOptimize, it takes around 300-500us, but 
when I comment it out, then it takes about 5us. It would still 
take some work to figure out how to get it to work with DMD.

```d
void DoNotOptimize(T)(T* ptr)
{
     import ldc.llvmasm;
     import core.volatile: volatileLoad;
     T value = volatileLoad(ptr);

     __asm("", "*mr,~{memory}", &value, );
}

void main() {
     import std.algorithm.iteration: sum;
     import std.array: uninitializedArray;
     import std.datetime.stopwatch;
     import std.random: uniform;
     import std.stdio: writeln;

     auto testData = uninitializedArray!(long[])(600_000);
     foreach(ref el; testData) el = uniform(0, 10);

     ulong seed = 0;
     ulong output = 0;
     StopWatch sw;
     sw.start();

     DoNotOptimize(&seed);
     output = testData.sum(seed);
     DoNotOptimize(&output);
     sw.stop();
     writeln("time: ", sw.peek);
}
```


More information about the Digitalmars-d-learn mailing list