简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM