1

I was using the timeit module to find the time expense of different calculations and wanted to find the squares of numbers. What is confusing is that the power operator (**) takes too much time as compared to multiplying the number by itself. I thought that since it was made specifically for that purpose, it might be faster. Also, the pow function slows down. Can anyone explain the reason behind this confusing results? Can anyone help?

>>> timeit.timeit('x*x; x = 999;', 'x=999', number=10**8)
6.830663157197719
>>> timeit.timeit('x**2; x = 999;', 'x=999', number=10**8)
27.047929744404712
>>> timeit.timeit('mul(x, x); x = 999;', 'from operator import mul; x=999', number=10**8)
12.522030856840132
>>> timeit.timeit('pow(x, 2); x = 999;', 'x=999', number=10**8)
36.16042014302741

Why is this so?

Some Name
  • 307
  • 2
  • 11
  • 4
    I'd recommend reading this (current question is a possible duplicate): http://stackoverflow.com/questions/1019740/speed-of-calculating-powers-in-python – Sharad Apr 12 '16 at 11:24

0 Answers0