C++ 與組語的速度...

Hacker News Daily 上看到「Why is this C++ code faster than my hand-written assembly for testing the Collatz conjecture?」覺得很有趣...

作者寫了一段 assembly,但跑起來比用 C++ 同義的版本慢多了。目前最高分的答案給了很清楚的解釋...

even:
    mov rbx, 2
    xor rdx, rdx
    div rbx

上面這段 code 是作者寫的組語版本,用到 div 指令,這是非常慢的指令:

On Intel Haswell, div r64 is 36 uops, with a latency of 32-96 cycles, and a throughput of one per 21-74 cycles.

相較於 C++ 的版本,用到的是 shr (logical shift right,以位元方式往右平移,最高位補零),速度快太多:

shr rax, 1 does the same unsigned division: It's 1 uop, with 1c latency, and can run 2 per clock cycle.

這是用到無號整數透過 shr 平移一格剛好是除以二的特性,因為速度的關係,這個用法到現在還是很常被拿來用,但對於平常沒在寫 assembly 的人就會有上面的誤解 XDDD

Leave a Reply

Your email address will not be published. Required fields are marked *