Avatar ·

为什么用于验证考拉兹猜想的C++代码比手写的内联汇编运行得更快?

大家好!我正在学习C++和汇编,并决定对大数验证考拉兹猜想(3n+1)。我编写了两个版本的代码:一个是纯C++并启用了优化,另一个是手动为x86-64编写的内联汇编。我原以为汇编会更快,但结果却相反。

这是我的C++代码(使用GCC的-O2编译):

#include <iostream>
#include <cstdint>

int collatz_steps(uint64_t n) {
    int steps = 0;
    while (n != 1) {
        if (n % 2 == 0) {
            n /= 2;
        } else {
            n = 3 * n + 1;
        }
        steps++;
    }
    return steps;
}

int main() {
    uint64_t max_n = 1000000;
    for (uint64_t i = 1; i <= max_n; ++i) {
        collatz_steps(i);
    }
    return 0;
}

这是带有内联汇编的版本(使用MSVC风格的__asm):

int collatz_asm(uint64_t n) {
    int steps = 0;
    __asm {
        mov rax, n
        xor ecx, ecx        ; st