You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Ruby中num >> 1的执行速度慢于num/2?

Ruby中位运算居然比算术运算慢?

我很惊讶,Ruby里num >> 1的执行速度居然比num/2慢——我一直以为位运算符应该比常规算术运算符更快。以下是Ruby 3.0.3版本的基准测试代码及结果:

# ruby 3.0.3

require "benchmark/ips"

Benchmark.ips do |bm|
    num = 1000000

    bm.report("num/2") do
        num/2
    end

    bm.report("num >> 1") do
        num >> 1
    end

    bm.compare!
end
# num/2:        16045584.8 i/s
# num >> 1:     14591335.3 i/s - 1.10x  slower


Benchmark.ips do |bm|
    num = 1000000

    bm.report("num * 2") do
        num * 2
    end

    bm.report("num << 1") do
        num << 1
    end

    bm.compare!
end
# num * 2:      18252815.2 i/s
# num << 1:     14289700.6 i/s - 1.28x  slower

内容的提问来源于stack exchange,提问作者Lam Phan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:42:45