From 3acb14ef462eebac8235c1043b2091abda91f931 Mon Sep 17 00:00:00 2001 From: xiver77 Date: Thu, 14 Jul 2022 23:06:06 +0900 Subject: [PATCH] Optimize `pcg32_random_r` utilizing more instruction level parallelism I had also sent you (the author) an email a while ago about the same issue. The original code has a chain of shift -> xor -> shift, while the modified code has a chain of shift | shift -> xor. Two shifts can run in parallel. Clang (14.0) does this optimization even with the original code, but GCC (12.1) doesn't, so it produces better code with manual optimization. You can compare the machine code output (https://godbolt.org/z/5bMjdsYnf). --- pcg_basic.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pcg_basic.c b/pcg_basic.c index 8c2fd0d..be6201e 100644 --- a/pcg_basic.c +++ b/pcg_basic.c @@ -61,7 +61,7 @@ uint32_t pcg32_random_r(pcg32_random_t* rng) { uint64_t oldstate = rng->state; rng->state = oldstate * 6364136223846793005ULL + rng->inc; - uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u; + uint32_t xorshifted = oldstate >> 27 ^ oldstate >> 45; uint32_t rot = oldstate >> 59u; return (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); }