Strange result with timeit execution time measurment
Ian Kelly
ian.g.kelly at gmail.com
Sat Nov 15 19:18:01 CET 2014
On Sat, Nov 15, 2014 at 10:07 AM, ast <nomail at invalid.com> wrote:
> Hi
>
> I needed a function f(x) which looks like sinus(2pi.x) but faster.
> I wrote this one:
>
> --------------------------
> from math import floor
>
> def sinusLite(x):
> x = x - floor(x)
> return -16*(x-0.25)**2 + 1 if x < 0.5 else 16*(x-0.75)**2 - 1
> --------------------------
>
> then i used module timeit to compare its execution time with math.sin()
> I put the sinusLite() function in a module named test.
>
> then:
>
>>>> import timeit
>>>> t1 = timeit.Timer("y=test.sinusLite(0.7)", "import test")
>>>> t2 = timeit.Timer("y=math.sin(4.39)", "import math") ## 4.39 =
>>>> 2*pi*0.7
>
>
>>>> t1.repeat(3, 1000000)
>
> [1.9994622221539373, 1.9020670224846867, 1.9191573230675942]
>
>>>> t2.repeat(3, 1000000)
>
> [0.2913627989031511, 0.2755561810230347, 0.2755186762562971]
>
> so the genuine sinus is much faster than my so simple sinLite() !
> Amazing isnt it ? Do you have an explanation ?
The built-in sin is written in C, and the C implementation on most
modern systems boils down to a single assembly instruction implemented
in microcode. That's generally going to be faster than a whole series
of operations written in Python. Even just doing the 2*pi
multiplication in Python will add a lot to the timing:
C:\>python -m timeit -s "import math" "math.sin(2*math.pi*0.7)"
1000000 loops, best of 3: 0.587 usec per loop
C:\>python -m timeit -s "import math" "math.sin(4.39)"
1000000 loops, best of 3: 0.222 usec per loop
More information about the Python-list
mailing list