Created
February 19, 2017 15:56
-
-
Save wilzbach/41f457e6238732ed4dfcef432c28653b to your computer and use it in GitHub Desktop.
walkBack: use Unqual & foreach vs. checking empty twice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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