[New-bugs-announce] [issue44376] Improve performance of integer exponentiation

Steven D'Aprano report at bugs.python.org
Thu Jun 10 08:12:15 EDT 2021


New submission from Steven D'Aprano <steve+python at pearwood.info>:

Naively, I assumed that `x**2` would be faster than `x*x` as there is only one name lookup in the first, and two in the second. But it is slower.

The performance of `x**2` relative to `x*x` has gradually deteriorated compared to `x*x` over many versions.

I have found the ratio of `x**2` to `x*x` using timeit:

    pythonX.Y -m timeit -s "x=115" "x**2"
    pythonX.Y -m timeit -s "x=115" "x*x"

for various X.Y:

2.4: 1.1  # ratio of time for x**2 / time for x*x
2.5: 1.5
2.6: 1.0
2.7: 1.6
3.2: 4.2
3.3: 4.2
3.5: 3.8
3.7: 5.9
3.9: 7.3


In the 2.x series, performance was quite close. In 3.x, the ratio has increased significantly. Either integer multiplication has gotten much faster, or exponentiation much slower, or both.

Shockingly (to me at least), an exponent of 1 is an order of magnitude slower than an multiplicand of 1:

2.7: 1.3  # ratio of time for x**1 / time for x*1
3.9: 10.2


Even an exponent of 10 is a little slower than repeated multiplication in 3.9:

`x*x*x*x*x*x*x*x*x*x` is slightly faster than `x**10`.


It would be nice if we could improve the performance of exponentiation.


(OS: Linux)

----------
components: Interpreter Core
messages: 395527
nosy: steven.daprano
priority: normal
severity: normal
status: open
title: Improve performance of integer exponentiation
type: performance
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44376>
_______________________________________


More information about the New-bugs-announce mailing list