how to benchmark pure functions?

Dennis dkorpel at gmail.com
Thu Oct 27 18:41:36 UTC 2022


On Thursday, 27 October 2022 at 17:17:01 UTC, ab wrote:
> How can I prevent the compiler from removing the code I want to 
> measure?

With many C compilers, you can use volatile assembly blocks for 
that. With LDC -O3, a regular assembly block also does the trick 
currently:

```D
void main()
{
     import std.datetime.stopwatch;
     import std.stdio: write, writeln, writef, writefln;
     import std.conv : to;

     void f0() {}
     void f1()
     {
         foreach(i; 0..4_000_000)
         {
             // nothing, loop gets optimized out
         }
     }
     void f2()
     {
         foreach(i; 0..4_000_000)
         {
             // defeat optimizations
             asm @safe pure nothrow @nogc {}
         }
     }
     auto r = benchmark!(f0, f1, f2)(1);
     writeln(r[0]); // 4 μs
     writeln(r[1]); // 4 μs
     writeln(r[2]); // 1 ms
}
```



More information about the Digitalmars-d-learn mailing list