Looping [was Re: Python and the need for speed]

bartc bc at freeuk.com
Mon Apr 17 20:52:30 EDT 2017


On 18/04/2017 01:23, Paul Rubin wrote:
> Ben Bacarisse <ben.usenet at bsb.me.uk> writes:
>>   c = sys.stdin.read(1)
>>   while c == ' ':
>>       c = sys.stdin.read(1)
>
> c = itertools.dropwhile(
>      lambda c: c==' ',
>      iter(lambda: sys.stdin.read(1),None)
>      ).next()
>

I tried this but it doesn't like the .next.

I wanted to see if it was any faster or slower than the more obvious loop.

(With the original loop, changing:

c=sys.stdin.read(1)
while c==' ':
     c=sys.stdin.read(1)

to:

r=sys.stdin.read

c=r(1)
while c==' ':
     c=r(1)

made it 75% faster (reading 10M spaces). Those 3 extra lookups per loop 
I guess (this was run inside a function otherwise the dynamics are 
different).

-- 
bartc



More information about the Python-list mailing list