[Tutor] finding square roots

Eric Brunson brunson at brunson.com
Sat Oct 6 00:09:27 CEST 2007


Alan Gauld wrote:
> "Eric Brunson" <brunson at brunson.com> wrote
>
>   
>>>>> import timeit
>>>>> t = timeit.Timer( "12 ** .5" )
>>>>> print t.timeit(10000000)
>>>>>           
>> 2.29147315025
>>     
>>>>> t = timeit.Timer( "sqrt(12)", "from math import sqrt" )
>>>>> print t.timeit(10000000)
>>>>>           
>> 7.17679214478
>>
>> Looks like ** is about three times faster than sqrt(), but that 
>> could be
>> the function overhead.
>>     
>
>   
>>>> timeit.Timer("import math; math.sqrt(64)").timeit(1000)
>>>>         
> 0.002298138362618829
>   
>>>> timeit.Timer("import math; 64 ** 0.5").timeit(1000)
>>>>         
> 0.018225722100503106
>
> I get the opposite result by includsing the importt in both
> timing sesions. Looks like it was the import that was slow.
> But that shouldn't affect real world usage sinmce you only
> do it once...
>   

Maybe I'm mis-remembering the documentation of timeit.  I thought the 
second argument to the Timer constructor was "setup code", i.e. code to 
be executed once before executing the first argument in the timing loop.

> Alan G.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list