Integer From A Float List?!?

Peter Otten __peter__ at web.de
Sun Mar 6 05:12:54 EST 2005


Michael Hoffman wrote:

>> $ py24 -m timeit -s "floats = map(float, range(1000))" -s"from itertools
>> import starmap, izip" "ints = list(starmap(int, izip(floats)))"
>> 1000 loops, best of 3: 343 usec per loop
> 
> Truly evil. Why is that faster than "ints = list(imap(int, floats))"?
> It is on my system.

A true performance anomaly. 

I can see how the lookup for int on every iteration may slow down [int(f)
for f in floats] with respect to map(int, floats) -- in fact the listcomp
approach becomes faster if you wrap it into a function:

def foo(int=int):
   return [int(f) for f in floats]

But where the advantage of the convoluted list(starmap(foo, izip(items))
could come from is a mystery to me. In particular, I would expect the
"pre-tupling" to slow down things -- which it sometimes does:

$ py24 -m timeit -s"t = (1,)" -s"def f(a): pass" "f(*t)"
1000000 loops, best of 3: 0.653 usec per loop
$ py24 -m timeit -s"t = 1" -s"def f(a): pass" "f(t)"
1000000 loops, best of 3: 0.471 usec per loop

and sometimes doesn't:

$ py24 -m timeit -s"t = 1.2" "int(t)"
1000000 loops, best of 3: 0.654 usec per loop
$ py24 -m timeit -s"t = (1.2,)" "int(*t)"
1000000 loops, best of 3: 0.657 usec per loop

Peter




More information about the Python-list mailing list