我应该使用乘法还是除法? [英] Should I use multiplication or division?

查看:56
本文介绍了我应该使用乘法还是除法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个愚蠢有趣的问题:

Here's a silly fun question:

假设我们必须执行一个简单的操作,我们需要一个变量值的一半.通常有两种方法可以做到这一点:

Let's say we have to perform a simple operation where we need half of the value of a variable. There are typically two ways of doing this:

y = x / 2.0;
// or...
y = x * 0.5;

假设我们使用语言提供的标准运算符,哪一个具有更好的性能?

Assuming we're using the standard operators provided with the language, which one has better performance?

我猜乘法通常更好,所以我在编码时尽量坚持,但我想确认这一点.

I'm guessing multiplication is typically better so I try to stick to that when I code, but I would like to confirm this.

尽管我个人对 Python 2.4-2.5 的答案很感兴趣,但也可以随意发布其他语言的答案!如果您愿意,也可以随意发布其他更好的方法(例如使用按位移位运算符).

Although personally I'm interested in the answer for Python 2.4-2.5, feel free to also post an answer for other languages! And if you'd like, feel free to post other fancier ways (like using bitwise shift operators) as well.

推荐答案

Python:

time python -c 'for i in xrange(int(1e8)): t=12341234234.234 / 2.0'
real    0m26.676s
user    0m25.154s
sys     0m0.076s

time python -c 'for i in xrange(int(1e8)): t=12341234234.234 * 0.5'
real    0m17.932s
user    0m16.481s
sys     0m0.048s

乘法快了 33%

路亚:

time lua -e 'for i=1,1e8 do t=12341234234.234 / 2.0 end'
real    0m7.956s
user    0m7.332s
sys     0m0.032s

time lua -e 'for i=1,1e8 do t=12341234234.234 * 0.5 end'
real    0m7.997s
user    0m7.516s
sys     0m0.036s

=> 没有真正的区别

LuaJIT:

time luajit -O -e 'for i=1,1e8 do t=12341234234.234 / 2.0 end'
real    0m1.921s
user    0m1.668s
sys     0m0.004s

time luajit -O -e 'for i=1,1e8 do t=12341234234.234 * 0.5 end'
real    0m1.843s
user    0m1.676s
sys     0m0.000s

=>仅快 5%

结论:在 Python 中,乘法比除法更快,但是当您使用更高级的 VM 或 JIT 更接近 CPU 时,优势就消失了.很有可能未来的 Python 虚拟机会让它变得无关紧要

conclusions: in Python it's faster to multiply than to divide, but as you get closer to the CPU using more advanced VMs or JITs, the advantage disappears. It's quite possible that a future Python VM would make it irrelevant

这篇关于我应该使用乘法还是除法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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