如果找到零,Python乘法表达式的计算速度会更快吗?
假设 ia 有一个带有大量被乘数(小表达式)的乘法表达式
expression = a*b*c*d*....*w
,例如 c 是 (x-1),d 是 (y**2-16),k 是 (xy-60)... .. x,y 是数字
我知道 c,d,k,j 可能为零
我编写表达式的顺序对于更快的评估是否重要?
写 cdkj...*w 更好还是 python 会计算所有表达式,无论我写的顺序如何?
suppose i a have a multiplicative expression with lots of multiplicands (small expressions)
expression = a*b*c*d*....*w
where for example c is (x-1), d is (y**2-16), k is (xy-60)..... x,y are numbers
and i know that c,d,k,j maybe zero
Does the order i write the expression matters for faster evaluation?
Is it better to write cdkj....*w or python will evaluate all expression no matter the order i write?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Python v2.6.5 不检查零值。
更新:我测试了Baldur 的表达式和 Python 可以并且将会优化涉及常量表达式的代码。 奇怪是
test6
没有优化。简而言之,如果表达式包含变量,则顺序并不重要。一切都会被评估。
Python v2.6.5 does not check for zero values.
Update: I tested Baldur's expressions, and Python can and will optimize code that involve constant expressions. The weird is that
test6
isn't optimized.In brief, if the expression includes variables, the order doesn't matter. Everything will be evaluated.
这只是 Python 3.1 中的快速检查:
在 Python 2.6 中也是如此:
所以订单确实会输入其中。
我还在 Python 3.1 中得到了这个结果:
到底为什么?
This is just a quick check in Python 3.1:
and this in Python 2.6:
So the order does enter into it.
Also I got this result in Python 3.1:
Why on Earth?
在进行基准测试之前不要尝试优化。
考虑到这一点,即使中间项为零,所有表达式都将被计算。
顺序可能仍然很重要。表达式从左到右计算。如果
a,b,c,...
是非常大的数字,它们可能会迫使 Python 分配大量内存,从而在到达j=0
之前减慢计算速度>。 (如果j=0
出现在表达式的前面,那么乘积永远不会变得那么大,并且不需要额外的内存分配)。如果在使用 timeit 或 cProfile,你觉得这可能是你的情况,那么你可以尝试预评估
c,d,k,j
和测试然后也使用
timeit
或cProfile
进行计时。真正判断这对您的情况是否有用的唯一方法是进行基准测试。尽管 PyPy 更快,但它似乎也没有对此进行优化:
Don't try to optimize before you benchmark.
With that in mind, it is true that all expressions will be evaluated even if an intermediate term is zero.
Order may still matter. Expressions are evaluated from left to right. If
a,b,c,...
are very large numbers, they could force Python to allocate a lot of memory, slowing down the calculation before it comes toj=0
. (Ifj=0
came earlier in the expression, then the product would never get as large and no additional memory allocation would be needed).If, after timing your code with timeit or cProfile, you feel this may be your situation, then you could try pre-evaluating
c,d,k,j
, and testingThen time this with
timeit
orcProfile
as well. The only way to really tell if this is useful in your situation is to benchmark.Although PyPy is much faster, it does not appear to optimize this either:
可能不会。乘法是最便宜的运算之一。如果 0 应该更快,那么就需要在之前检查零,这可能比仅仅进行乘法要慢。
最快的解决方案应该是
multiply.reduce()
Probably not. Multiplication is one of the cheapest operations of all. If a 0 should be faster then it would be necessary to check for zeros before and that's probably slower than just doing the multiplication.
The fastest solution should be
multiply.reduce()