Hi Dhananjay,
On Tuesday 30 April 2013 10:23 PM, Dhananjay Nene wrote:
>
> ....[snip]...
> Thanks steve for setting up an interesting observation.
> Yes, it is peculiar. I defined another function pair2 (which had a minor change
> compared to pair)
>
> def pairs2(s):
> try :
> i = iter(s)
> while True :
> yield next(i) + next(i)
> except StopIteration :
> pass
>
> I was just trying to avoid creation of two temporary variables here.
>
> On Python 2.7.3 I got
>
> >>> timeit.timeit('":".join(pairs("0x21000024ff3afd2b"))', setup='from __main__
> import pairs')
> 4.479202032089233
> >>> timeit.timeit('":".join(pairs2("0x21000024ff3afd2b"))', setup='from
> __main__ import pairs2')
> 4.3042449951171875
> >>> timeit.timeit('":".join(s[i:i+2] for i in range(2, len(s), 2))',
> setup='s="0x21000024ff3afd2b"')
> 1.9831359386444092
> >>> timeit.timeit("':'.join( a+b for a, b in zip(s[::2], s[1::2]) )",
> setup='s="0x21000024ff3afd2b"')
> 2.999051809310913
>
>
I have a feeling this has something to do with the function call overhead, because:
>>> timeit.timeit('":".join(pairs("0x21000024ff3afd2b"[2:]))', setup='from
__main__ import pairs')
9.249284982681274
>>> timeit.timeit('":".join(pairs2("0x21000024ff3afd2b"[2:]))', setup='from
__main__ import pairs2')
9.641417026519775
>>> timeit.timeit("':'.join( next(i) + next(i) for _ in s[2:] )",
setup="s='0x21000024ff3afd2b'; i = iter(s[2:])")
2.451604127883911
>>>
cheers,
- steve