I am trying to optimize my Python code. Between:
y = x*x
or
y = x**2
if I need one trillion iterations in a speed-critical program, which one should I choose?
I am trying to optimize my Python code. Between:
y = x*x
or
y = x**2
if I need one trillion iterations in a speed-critical program, which one should I choose?
x**2
is faster than x*x
.
Implementation of exponent has some overhead in Python, so it is usually faster to use your custom multiplication O(n)
with small multiplication count. x*x*x*x*x
is way faster than x**5
. Exponent time is a sort of constant. Your multiplication time is increasing with exponent parameter, so with a large parameter it is better to use exponent. However, with really very small parameter (2, in your case), exponent is faster than multiplication. And x**2
is faster than x*x
, although x**3
is way slower than x*x*x
. You can find a nice benchmark in this answer.
x*x
can be faster than x**2
. It seems you meant the reverse of what you said. –
Photogene © 2022 - 2024 — McMap. All rights reserved.
x*x
was faster thanx**2
. – Photogenex*x
is about 3.5x faster thanx**2
. Although lines of opcodes are equal viadis
module, the implementations differ. In CPythonceval.c
,x*x
usesPyNumber_Multiply
andbinary_op1
whilex**2
usesPyNumber_Power
andternary_op
. It's not clear to me where the slow down occurs, but the latter is more complex. – Kathikathiawar