how to benchmark pure functions?
max haughton
maxhaton at gmail.com
Sat Oct 29 22:12:01 UTC 2022
On Thursday, 27 October 2022 at 18:41:36 UTC, Dennis wrote:
> 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
> }
> ```
I recommend a volatile data dependency rather than injecting
volatile ASM into code FYI i.e. don't modify the pure function
but rather make sure the result is actually used in the eyes of
the compiler.
More information about the Digitalmars-d-learn
mailing list