Avatar ·

Why C++ code for testing the Collatz conjecture runs faster than a hand-written assembly inline?

Hello everyone! I am learning C++ and assembly, and I decided to test the Collatz conjecture (3n+1) for large numbers. I wrote two versions of the code: one in pure C++ with optimizations, and the second with a hand-written assembly inline for x86-64. I expected the assembly to be faster, but I got the opposite result.

\n\n

Here is my C++ code (compiled with -O2 in GCC):

\n
#include <iostream>\n#include <cstdint>\n\nint collatz_steps(uint64_t n) {\n    int steps = 0;\n    while (n != 1) {\n        if (n % 2 == 0) {\n            n /= 2;\n        } else {\n            n = 3 * n + 1;\n        }\n        steps++;\n    }\n    return steps;\n}\n\nint main() {\n    uint64_t max_n = 1000000;\n    for (uint64_t i = 1; i <= max_n; ++i) {\n        collatz_steps(i);\n    }\n    return 0;\n}
\n