[Tutor] finding square roots
Alan Gauld
alan.gauld at btinternet.com
Sat Oct 6 00:55:48 CEST 2007
"Eric Brunson" <brunson at brunson.com> wrote
>>>>>> t = timeit.Timer( "sqrt(12)", "from math import sqrt" )
>>>>>> print t.timeit(10000000)
>>> 7.17679214478
>>>>> 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 sessions. Looks like it was the import that was slow.
>
> 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.
It seems to suggest that, so I don't understand the reason,
but in any case its a fairer comparison to include the import in both
tests.
Doing it your way gives me:
>>> timeit.Timer("64 ** 0.5", "import math").timeit(1000)
0.00039243745641215355
>>> timeit.Timer("math.sqrt(64)", "import math").timeit(1000)
0.00062668800364917843
>>>
Which favours ** but by a smaller margin.
Interesting,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list