Henry Kim
Henry Kim

Reputation: 585

Why v*v is faster than v**2 in python

I tried to measure the performance between v*v and v**2. And the result was just like below

# test was generated with randint(1, 999)

# 0.10778516498976387
print(timeit.timeit("sum([item*item for item in test])", number=10000, setup="from __main__ import test"))

# 0.35526178102009
print(timeit.timeit("sum([item**2 for item in test])", number=10000, setup="from __main__ import test"))

The reason that I started this experimentation was I don't want to do the same operation in the list comprehension.

Since the operator appears once, (for example, (item-3) * (item*3) and (item-3)**2) I thought (item-3)**2 will be faster than (item-3)*(item-3). But it was totally opposite.

Can anyone explain why?

[+] I used python3.6.0

Upvotes: 4

Views: 724

Answers (1)

Alistair Carscadden
Alistair Carscadden

Reputation: 1228

Since * is an arithmetic operation deeply rooted in processors and ** is a wrapper for the pow function.

Using k ** 2 has more overhead than k * k since python will internally call the pow function.

Upvotes: 5

Related Questions