现代cpus是否将乘法跳过零? [英] Do modern cpus skip multiplications by zero?

查看:107
本文介绍了现代cpus是否将乘法跳过零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当前cpus是否避免在两个数字中至少有一个为零的情况下将它们相乘。谢谢

I would like to know if current cpus avoid multiplying two numbers when at least one of them is a zero. Thanks

推荐答案

具体取决于CPU和(在某些情况下)操作数的类型。

This varies widely depending on the CPU and (in some cases) the type(s) of the operands.

较旧/较简单的CPU通常使用以下乘法算法:

Older/simpler CPUs typically use a multiplication algorithm something like this:

integer operator*(integer const &other) {
    unsigned temp1 = other.value;
    unsigned temp2 = value;
    unsigned answer = 0;

    while (temp1 != 0) {
        if (temp1 & 1) 
            answer += temp2;
        temp2 <<= 1;
        temp1 >>=1;
    }
    return integer(answer);
}

因为循环仅在/如果 temp1才执行! = 0 时,如果 temp1 以0开头(显然,此处不会尝试任何优化),则显然不会执行循环。其他操作数为0)。

Since the loop executes only when/if temp1 != 0, the loop obviously won't execute if temp1 starts out as 0 (but as written here, won't attempt any optimization for the other operand being 0).

但是,从根本上讲,这只是一次一点算法。例如,当乘以32位操作数时,如果每个位都有50:50的机会被设置,则我们期望平均大约进行16次迭代。

That, however, is fundamentally a one bit at a time algorithm. For example, when multiplying 32-bit operands, if each bit has a 50:50 chance of being set, we expect approximately 16 iterations on average.

更新的高-端CPU通常一次至少可以使用两个位,甚至可能更多。它通常不是使用单个硬件执行多次迭代,而是使用乘法的每个阶段使用单独的(尽管,基本上是相同的)硬件对操作进行流水线化(尽管在正常的流水线图中,这些硬件通常不会显示为单独的阶段)

A newer, high-end CPU will typically work with at least two bits at a time, and perhaps even more than that. Instead of a single piece of hardware executing multiple iterations, it'll typically pipeline the operation with separate (albeit, essentially identical) hardware for each stage of the multiplication (though these won't normally show up as separate stages on a normal pipeline diagram for the processor).

这意味着执行将具有相同的延迟(和吞吐量),而与操作数无关。平均而言,它可以稍微提高延迟,并提高吞吐量,但是无论操作数如何,都会导致每个操作以相同的速度发生。

This means the execution will have the same latency (and throughput) regardless of the operands. On average it improves latency a little bit and throughput a lot, but does lead to every operation happening at the same speed, regardless of operands.

这篇关于现代cpus是否将乘法跳过零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆