On 23/10/2023 15:30, Georg-Johann Lay wrote:
For the C code below, I am getting execution times of around 8 to 8.3 seconds with gcc (v11.3 and v13.2) and around 5 seconds with clang v17. Only options I used were -O3 (-Os or -Ofast didn't make a difference). Architecture is x86_64-linux-gnu, Dual Core Intel Core2 I ran the code below with > gcc coll.c -o coll.x -O3 && time -p ./coll.x I wouldn't ask this question if I hadn't observed similar thing with other programs already, any I am wondering if I am missing something crucial like supplying GCC with better options? After all, it's that GCC's code is 60% (or more) slower than clang's. I'd guess +-5% is well in the range of noise, but +60% or more ??? Johann
The only noticeable difference I saw in the generated assembly with a quick test on godbolt is that clang uses a conditional move to implement the ternary expression, while gcc uses a conditional branch. The branching here might be overwhelming the speculative execution - after all, it is not a very predictable expression (or there'd be no point in your program).
If my speculative theory is correct, I don't know how to encourage gcc to generate a cmove here - perhaps giving it more information about the actual target processor with "-march=native" will improve the choice of instructions.
But if you are hoping to find a counterexample to the Collatz conjecture, you'll need to move to "unsigned __uint128", since it's been checked up to about 2 ** 68 :-)
mvh., David
--- C99 Code: #include <inttypes.h> #include <stdio.h> #include <stdlib.h> uint32_t coll (uint64_t i) { for (uint32_t n = 0; ; ++n) { if (i == 1) return n; if (i > UINT64_MAX / 3 - 3) { fprintf (stderr, "%" PRIu64 " = %" PRIx64 " too big\n", i, i); exit (1); } i = (i & 1) ? (3 * i + 1) >> 1 : i >> 1; } } int main (void) { uint64_t n = 0x1000000; uint64_t i0 = 0x2000000; uint32_t max_it = 0; for (uint64_t i = i0; i <= i0 + n; ++i) { uint32_t it = coll (i); if (it > max_it) { printf ("%" PRIu64 ": %" PRIu32 "\n", i, it); max_it = it; } } return 0; }