用乘法和除法移位运算符用C实际上更快吗? [英] Is multiplication and division using shift operators in C actually faster?

查看:187
本文介绍了用乘法和除法移位运算符用C实际上更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

乘法和除法可以使用​​位操作来实现,例如:

Multiplication and division can be achieved using bit operators, for example

i*2 = i<<1
i*3 = (i<<1) + i;
i*10 = (i<<3) + (i<<1)

等。

它实际上是更快地使用说(I&LT;&LT; 3)+(I&LT;&LT; 1)用10乘以比使用我* 10 直接?有任何种类的输入不能被乘或以这种方式分割

Is it actually faster to use say (i<<3)+(i<<1) to multiply with 10 than using i*10 directly? Is there any sort of input that can't be multiplied or divided in this way?

推荐答案

简短的回答:不会吧

长一点的回答:
你的编译器中有一个优化知道如何以最快的速度目标处理器架构能够繁殖。最好的办法就是明确告诉编译器你的意图(即我* 2,而不是I&LT;&LT; 1),并让它决定最快汇编/机器code序列是什么。它甚至可能是处理器本身执行的乘法指令为转移&放大器的序列;增加了在微code。

Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.

底线 - 不要花很多时间担心这个。如果你的意思移位,移位。如果你的意思繁殖,繁殖。做什么是语义清晰的 - 你的同事以后会感谢你。或者,更可能的是,如果你这样做,否则诅咒你以后。

Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.

这篇关于用乘法和除法移位运算符用C实际上更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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