9

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?

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
kmonsoor
  • 7,600
  • 7
  • 41
  • 55
  • 2
    @ChrisHayes: I actually done it for [Gauss-Legendre Algorithm in python](http://stackoverflow.com/a/347749/4279). At the time `x*x` was faster than `x**2`. – jfs Dec 25 '13 at 21:31
  • 1
    @TonyHopkinson Python is used in a lot of scientific computing, despite being agonizingly slow (usually it is used to call optimized libraries like numpy). – Aleksandr Dubinsky Dec 25 '13 at 22:00
  • 3
    You ever see the code the mathmeticians and engineers write? Microoptimisation is the least of their problems. :( – Tony Hopkinson Dec 26 '13 at 00:44
  • 4
    @roippi et al. even after more than 4 years, I'm yet to understand why this question is "off-topic". Someone plz enlighten me or remove the "off-topic" honor. – kmonsoor Mar 20 '18 at 15:59
  • 3
    This seems like a legitimate question. On Python 3.6, `x*x` is about 3.5x faster than `x**2`. Although lines of opcodes are equal via `dis` module, the implementations differ. In CPython `ceval.c`, `x*x` uses [`PyNumber_Multiply`](https://github.com/python/cpython/blob/31fb351211cb9c81d5878ad3518b3a7bf0211473/Objects/abstract.c#L959) and `binary_op1` while `x**2` uses [`PyNumber_Power`](https://github.com/python/cpython/blob/31fb351211cb9c81d5878ad3518b3a7bf0211473/Objects/abstract.c#L1002) and `ternary_op`. It's not clear to me where the slow down occurs, but the latter is more complex. – pylang Jun 23 '19 at 00:38

1 Answers1

3

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.

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
gthacoder
  • 2,213
  • 3
  • 15
  • 17
  • 8
    [`x*x` can be faster than `x**2`](http://stackoverflow.com/questions/20776706/python-which-one-is-faster-between-x2-or-xx#comment31142323_20776706). It seems you meant the reverse of what you said. – jfs Dec 25 '13 at 21:31
  • 1
    x**2 is a special case, and the speed difference in my tests was pretty small. So I guess it can also depend on x. – gthacoder Dec 25 '13 at 21:42