Static typing [was Re: Python and the need for speed]

justin walters walters.justin01 at gmail.com
Sun Apr 16 11:00:14 EDT 2017


On Sun, Apr 16, 2017 at 3:55 AM, bartc <bc at freeuk.com> wrote:

> Example C of the same silly program in Python:
>
> def add(a,b):
>     return a+b
>
> def testfn():
>     sum=a=b=0
>     for i in range(100000000):
>         sum += add(a,b)
>         a += 1
>         b += 2
>
>     print (a,b,sum)
>
> testfn()
>
>
> Timings:
>
> A (Pure HLL**)          13   seconds      (dynamic/interpreted)
> A (With ASM module)      3
> A (With ASM module)      2                (older version; hmmm...)
>
> B (my compiler)          0.5              (static/compiled)
> B (via C/gcc-O3)         0.14
>
> C (Python 2)           163
> C (Python 2/xrange)     30
> C (Python 3)            38
> C (Pypy)                 5
>


Just for fun I wanted to write this up in Nim to compare execution time.
Nim has Python-esqe syntax but is statically
typed and compiled. I think this is relevant to the discussion.

Code looks like this:

```
import times

proc add(a, b: int): int =
    result = a + b

proc test() =
    var
        sum = 0
        a = 0
        b = 0
    for i in 0..<100000000:
        sum += add(a, b)
        a += 1
        b += 1
    echo "a: " & $a & " b: " & $b & "\n"
    echo "Sum: " & $sum

when isMainModule:
    var t0 = cpuTime()
    test()
    var t1 = cpuTime()
    echo "***Execution Time: " & $(t1 - t0) & "***\n"
```


No optimization: ***Execution Time: 2.876923***
Optimized for speed: ***Execution Time: 2.844163***
Optimized for size: ***Execution Time: 2.844901***
Release option: ***Execution Time: 2.844021***

So, generally around 2.8 seconds.

Not too bad for a GC'd language. There are probably some more optimizations
I could make to improve execution time.



More information about the Python-list mailing list