3 ms·
A quick detour to Godbolt shows all three loop_v4 versions result in exactly identical code, on all the compilers I tried. And, all used the condition code matc
by ncmncm 5y ago
A quick detour to Godbolt shows all three loop_v4 versions result in exactly identical code, on all the compilers I tried. And, all used the condition code matching the sign bit, directly, so did not do a right shift. All used cmov to select a function to call. (On ARM they used csel, equivalently.)
Running under Google Benchmark, I get:
$ g++ -O2 b.cc -L benchmark/build/src -lbenchmark \
> -I benchmark/include -lpthread -o b -march=skylake bf.o
$ ./b
...
-----------------------------------------------------
Benchmark Time CPU Iterations
-----------------------------------------------------
v1 244 ns 244 ns 2640782
v1a 245 ns 245 ns 2861829
v2 251 ns 251 ns 2761882
v2a 250 ns 250 ns 2775107
v3 264 ns 264 ns 2634478
v3a 263 ns 263 ns 2646271
v4 246 ns 246 ns 2812437
v4a 231 ns 231 ns 3042318
The "a" versions are without the redundant check for (i >= 0). They are mostly the same, here, except v4a. The func_false and func_true functions are linked in from bf.o.
$ clang++-11 -O2 b.cc -L benchmark/build/src -lbenchmark \
> -I benchmark/include -lpthread -o b -march=skylake bf.o
$ ./b
...
v1 282 ns 282 ns 2314149
v1a 282 ns 282 ns 2496325
v2 239 ns 239 ns 2939233
v2a 253 ns 253 ns 2767869
v3 277 ns 277 ns 2525156
v3a 242 ns 242 ns 2874514
v4 254 ns 254 ns 2753859
v4a 222 ns 222 ns 3157533
Interesting here is that Clang ends up with the best time, after starting off way behind. (The v2/v2a thing is some kind of testing artifact.)
Benchmarking almost always produces surprising results. It could be just good luck that mine came out fastest.