正在转向位比相乘,并在Java中分裂速度更快? 。净? [英] Is shifting bits faster than multiplying and dividing in Java? .NET?

查看:169
本文介绍了正在转向位比相乘,并在Java中分裂速度更快? 。净?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

移位左右明显高于乘除运算速度快于大多数(所有?)的CPU,如果你碰巧使用2的幂然而,它可以减少code的清晰度对一些读者和一些算法。是位移性能真的有需要,我也可以期望编译/ VM,以通知的情况下并对其进行优化(尤其是当的-2功率是文字)?我主要感兴趣的是Java和.NET行为,但受欢迎的见解其他语言的实现也是如此。

Shifting bits left and right is apparently faster than multiplication and division operations on most (all?) CPUs if you happen to be using a power of 2. However, it can reduce the clarity of code for some readers and some algorithms. Is bit-shifting really necessary for performance, or can I expect the compiler/VM to notice the case and optimize it (in particular, when the power-of-2 is a literal)? I am mainly interested in the Java and .NET behavior but welcome insights into other language implementations as well.

推荐答案

大多数编译器现在会做更多的转换乘或除通过上电即用两到移位操作。当优化,许多编译器可以优化乘法或除法与编译时间常数,即使它不是2的功率往往是一个乘法或除法可以分解为一系列的变化,并补充说,如果这一连串的动作会更快比乘法或除法,编译器将使用它。

Most compilers today will do more than convert multiply or divide by a power-of-two to shift operations. When optimizing, many compilers can optimize a multiply or divide with a compile time constant even if it's not a power of 2. Often a multiply or divide can be decomposed to a series of shifts and adds, and if that series of operations will be faster than the multiply or divide, the compiler will use it.

有关一个常数师,编译器通常可以操作由一个幻数后面的转变转换为乘法。这可以是一个主要的时钟周期的保护,因为乘法比除法运算常常要快得多。

For division by a constant, the compiler can often convert the operation to a multiply by a 'magic number' followed by a shift. This can be a major clock-cycle saver since multiplication is often much faster than a division operation.

亨利·沃伦的书,黑客的喜悦,对这个话题的大量信息,其中也包括相当以及在配套网站:

Henry Warren's book, Hacker's Delight, has a wealth of information on this topic, which is also covered quite well on the companion website:

又见讨论(带有链接或两个)的:

See also a discussion (with a link or two ) in:

总之,这一切都归结为让编译器利用微优化的繁琐细节。因为这样做你自己的转变扑空编译它已经多年。

Anyway, all this boils down to allowing the compiler to take care of the tedious details of micro-optimizations. It's been years since doing your own shifts outsmarted the compiler.

这篇关于正在转向位比相乘,并在Java中分裂速度更快? 。净?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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