Skip to content

Instantly share code, notes, and snippets.

@wilzbach
Created February 19, 2017 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilzbach/41f457e6238732ed4dfcef432c28653b to your computer and use it in GitHub Desktop.
Save wilzbach/41f457e6238732ed4dfcef432c28653b to your computer and use it in GitHub Desktop.
walkBack: use Unqual & foreach vs. checking empty twice
> ldc -O5 -release -boundscheck=off walkBack.d && ./walkBack
walkBack.foreach = 3 secs, 772 ms, 463 μs, and 6 hnsecs
walkBack.while = 4 secs, 191 ms, 417 μs, and 8 hnsecs
import std.algorithm, std.conv, std.datetime, std.functional, std.range, std.stdio, std.traits, std.typecons;
private void doNotOptimizeAway(T)(auto ref T t)
{
import core.thread : getpid;
import std.stdio : writeln;
if(getpid() == 1) {
writeln(*cast(char*)&t);
}
assert(t == 99_999);
}
void main()
{
auto n = 100_000;
auto range = n.iota!size_t.array;
alias Range = typeof(range);
writeln("starting benchmark");
auto bench = benchmark!(
{ doNotOptimizeAway({
Unqual!(ElementType!Range) last;
foreach (e; range)
last = cast(Unqual!(ElementType!Range)) e;
return last;
}());},
{ doNotOptimizeAway({
while(!range.empty){
auto element = range.front;
range.popFront();
if(range.empty) return element;
}
return range.front;
}());},
)(1_000_000_000);
string[] names = ["walkBack.foreach", "walkBack.while"];
foreach(j,r;bench)
writefln("%-15s = %s", names[j], r.to!Duration);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment