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

Steve D'Aprano steve+python at pearwood.info
Sun Apr 16 13:13:18 EDT 2017


On Mon, 17 Apr 2017 02:20 am, justin walters wrote:

> On Sun, Apr 16, 2017 at 8:46 AM, bartc <bc at freeuk.com> wrote:
> 
>> What were the results with Python on your machine?
> 
> 
> 
> Well, at first I tried to implement it with a generator. I gave up on
> waiting for the program to complete
> after about 6 minutes.

That seems... excessive.

For what it's worth, on my machine (2GB RAM and 1.2GHz CPU) I can add up 100
million ints in 14 seconds:

py> with Stopwatch():
...     sum(range(100000000))
...
4999999950000000
time taken: 14.032116 seconds

which isn't fast but it's within an order of magnitude of fast. What's a
factor of ten between friends?

Of course the built-in sum() is a bit faster than the version Bart uses.
It's almost like he is deliberately writing the least efficient Python code
he can... (or maybe he just doesn't know Python very well). Here's his
version again (slightly adapted):


def add(a, b):
    return a + b

def testfn():
    total = a = b = 0
    for i in range(100000000):
        total += add(a, b)
        a += 1
        b += 2
    return (a, b, total)


And the results:

py> with Stopwatch():
...     testfn()
...
(100000000, 200000000, 14999999850000000)
time taken: 93.543194 seconds


If I can run Bart's test on my slow old computer in a minute and a half, my
guess is that your generator must have been doing something terribly wrong
to still not be complete after six minutes.


The timer I used (Stopwatch) is basically this:

http://code.activestate.com/recipes/577896-benchmark-code-with-the-with-statement/



> After using your code almost exactly I get:
>>>> Sum:  14999999850000000
>>>> ***Execution Time:  17.33912420272827 ***
> 
> That's with Python 3.5 on an Intel I5-6600k 3.9Ghz cpu and 16GB DDR4
> memory.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.



More information about the Python-list mailing list