how to benchmark pure functions?

H. S. Teoh hsteoh at qfbox.info
Thu Oct 27 18:34:28 UTC 2022


On Thu, Oct 27, 2022 at 06:20:10PM +0000, Imperatorn via Digitalmars-d-learn wrote:
> On Thursday, 27 October 2022 at 17:17:01 UTC, ab wrote:
> > Hi,
> > 
> > when trying to compare different implementations of the optimized
> > builds of a pure function using benchmark from
> > std.datetime.stopwatch, I get times equal to zero, I suppose because
> > the functions are not executed as they do not have side effects.
> > 
> > The same happens with the example from the documentation:
> > https://dlang.org/library/std/datetime/stopwatch/benchmark.html
> > 
> > How can I prevent the compiler from removing the code I want to
> > measure?  Is there some utility in the standard library or pragma
> > that I should use?
[...]

To prevent the optimizer from eliding the function completely, you need
to do something with the return value.  Usually, this means you combine
the return value into some accumulating variable, e.g., if it's an int
function, have a running int accumulator that you add to:

	int funcToBeMeasured(...) pure { ... }

	int accum;
	auto results = benchmark!({ 
		// Don't just call funcToBeMeasured and ignore the value
		// here, otherwise the optimizer may delete the call
		// completely.
		accum += funcToBeMeasured(...);
	});

Then at the end of the benchmark, do something with the accumulated
value, like print out its value to stdout, so that the optimizer doesn't
notice that the value is unused, and decide to kill all previous
assignments to it. Something like `writeln(accum);` at the end should do
the trick.


T

-- 
Indifference will certainly be the downfall of mankind, but who cares? -- Miquel van Smoorenburg


More information about the Digitalmars-d-learn mailing list