Skip to content

Instantly share code, notes, and snippets.

@wilzbach
Last active August 5, 2016 00:17
Show Gist options
  • Save wilzbach/c8dd833fd6f2df43604b9c6b0cd0dff4 to your computer and use it in GitHub Desktop.
Save wilzbach/c8dd833fd6f2df43604b9c6b0cd0dff4 to your computer and use it in GitHub Desktop.
setBit at runtime and compile-time
auto setBit(ubyte idx)(ulong bitfield)
{
enum mask = 1UL << idx;
return bitfield |= mask;
}
ulong setBit(ulong bitfield, ulong idx)
{
ulong mask = 1UL << idx;
return bitfield |= mask;
}
private void doNotOptimizeAway(T)(auto ref T t)
{
import core.thread : getpid;
import std.stdio : writeln;
if(getpid() == 1) {
writeln(*cast(char*)&t);
}
}
__gshared ulong r;
void main()
{
import std.datetime: benchmark, Duration;
import std.stdio : writefln;
import std.conv : to;
ulong bitfield = 42_000;
ubyte idx = 10;
auto bench = benchmark!(
{ r += setBit(bitfield, idx); },
{ r += setBit!10(bitfield); },
)(2_000_000_000);
string[] names = ["setbit.runtime", "setbit.ctfe"];
foreach(j,r;bench)
writefln("%-14s = %s", names[j], r.to!Duration);
}
> dmd -release -O -boundscheck=off foo.d main.d && ./main
setbit.runtime = 6 secs, 176 ms, 765 μs, and 7 hnsecs
setbit.ctfe = 5 secs, 427 ms, 177 μs, and 1 hnsec
> ldmd -inline -release -O3 -boundscheck=off main.d && ./main
setbit.runtime = 1 sec, 374 ms, 360 μs, and 5 hnsecs
setbit.ctfe = 676 ms, 810 μs, and 4 hnsecs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment