优化模量操作 [英] Optimising modulus operation

查看:115
本文介绍了优化模量操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用2的整数倍进行除数时,我们可以通过执行右移来优化运算.

例如

i = i >> 3;

等效于

i = i/8;

我的问题是:

*这样做可能会带来切实的好处,还是编译器(在我的情况下为gcc)会优化这种情况?

*当使用已知值乘以2的倍数时,是否可以对模运算进行类似的优化?

When performing division by a constant that is a multiple of 2 we can optimise the operation by performing a right shift.

eg

i = i >> 3;

is equivalent to

i = i / 8;

My questions are:

* Is there likely to be a tangible benefit to doing this or would a compiler (gcc in my case) make this optimisation?

* Is it possible to perform a similar optimisation to the modulus operation when working with a known value that is a multiple of 2?

推荐答案

当您编写等效的按位移位运算时微操作仅需由ALU(CPU)执行一次微操作.它采用提供的值的二进制表示形式,并执行单个移位"微操作.

但是,当您编写除法(float)时,根据使用的CPU类型及其指令集,它会转换为单个移位"微操作或多个微操作.因此可能需要更多时间.

使用最新的高级CPU,其中所有浮点/整数除法(以及所有其他数据类型的操作)都硬连线",执行第一操作的时间增益几乎可以忽略不计.

我想看看别人在这方面怎么说.我读了这么长的书(在大学时代:-D),因此,如果我无意中输入了错误的单词,我们深表歉意.
When you write bitwise shift operation equivalent microoperation takes only one micro-operation to be performed by the ALU(CPU). It takes binary representation of the value supplied and performs a single "shift" micro operation.

But when you write a division(float) it is converted into either a single "shift" micro operation or multiple micro opearation depending upon the kind of CPU in use and its instruction set. Hence likely to take more time.

With the latest advance CPU where all floating point/interger division ( along with all other data type operation ) "hardwired" , the time gain doing the first operation is almost neglegible.

I would like to get to see what others say in this regard. I read all this long back(in college days :-D ), so apologise if I have made a wrong word un-intentionally.


Josh Gray写道:
Josh Gray wrote:

*这样做可能会带来切实的好处,还是编译器(在我的情况下为gcc)会对此有所优化?

* Is there likely to be a tangible benefit to doing this or would a compiler (gcc in my case) make this optimisation?


VC++编译器负责这种优化(我看不到div操作).
我想gcc会做同样的事情,您可以使用-S开关并查看生成的汇编文件来验证它.


VC++ compiler takes care of such optimization (I see no div operation).
I guess gcc do the same, you may verify it using the -S switch and looking at the assembly file produced.

Josh Gray写道:
Josh Gray wrote:

*当使用2的倍数的已知值时,是否可以对模运算进行类似的优化?

* Is it possible to perform a similar optimisation to the modulus operation when working with a known value that is a multiple of 2?


是的,例如


Yes, for instance

i = i & 7;


等价于


is equivalent to

i = i % 8;


对于i的正值(让编译器为您优化的一个优点是,它也会自动处理负数).

[添加]
我当然假设整数操作.
[/添加]

:)


for positive values of i (an advantage of letting the compiler optimize for you, is the automatically handling of the negative numbers too).

[added]
I assume integer operation, of course.
[/added]

:)


这篇关于优化模量操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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