[SciPy-user] Speed differences in sqrt calculation: what is good to know

Anne Archibald peridot.faceted@gmail....
Thu Jun 12 14:06:49 CDT 2008


2008/6/11 Ivo Maljevic <ivo.maljevic@gmail.com>:
> 2008/6/11 David Cournapeau <david@ar.media.kyoto-u.ac.jp>:
>>
>> Ivo Maljevic wrote:
>> > Based on comments from Gael Varoquaux and David Cournapeau , I did the
>> > execution time test.
>> > At least for me, it is clear that if the number is a real scalar, AND
>> > the expected result is also real,
>> > the best way is to call the math version of sqrt() function. The
>> > differences are more than significant, as you can see:
>> >
>>
>> It is expected for numpy/scipy functions to be much slower than python
>> *for scalar*. Since they are optimized to be used with arrays, you are
>> paying the cost to initialize the machinery to handle arrays (ufunc),
>> without the benefit.
>
> No disagreement there. My comment, which I realize was probably unnecessary,
> is that
> one has to pay attention as to which version of the function is called.
> Since I started SciPy I always used everything from it, never even thinking
> that math.sqrt(), math.sin(), etc., are faster if I'm working with scalar
> values. And there are always coefficients or scaling parameters that do not
> need to be in a vector form.

Keep in mind that if you are doing many computations, doing them with
scalars exposes you to a great deal of overhead from the python
interpreter. Put another way, if you're writing a program in which you
compute enough square roots that the speed difference between
math.sqrt and numpy.sqrt is significant, you should almost certainly
rewrite your program so that you are computing vector square roots;
the time you save in python overhead will make your program vastly
faster. In fact it is probably difficult to write anontrivial program
in which the time spent computing scalar square roots is significant.

Anne


More information about the SciPy-user mailing list