Author steven.daprano
Recipients steven.daprano
Date 2021-06-10.12:12:15
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
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)
Date User Action Args
2021-06-10 12:12:15steven.dapranosetrecipients: + steven.daprano
2021-06-10 12:12:15steven.dapranosetmessageid: <>
2021-06-10 12:12:15steven.dapranolinkissue44376 messages
2021-06-10 12:12:15steven.dapranocreate