map vs. list-comprehension

Stelios Xanthakis sxanth at ceid.upatras.gr
Fri Jul 1 14:22:37 EDT 2005


Mandus wrote:

> jepp - faster, but still slower than the map.
> 
> 1000000 iterations:
>  zip+list-comprehension: 8.1s
>  izip+list-comprehension: 7.5s
>  map: 7.0s
> 

Strange. On 2.4.1 izip is the fastest.
The thing is that if you put benchmark code in global the
results are not fair as each variable access is a LOAD_GLOBAL
and costs a dictionary lookup.  That can lead to wrong
results, like that 'try ... except ..' is faster than
'if i in ..'.

With this benchmak:

#--------------------------------------------------------
from itertools import izip
from time import time

def f1():
     return map(lambda bb,ii,dd: bb+ii*dd,b,i,d)
def f2():
     return [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ]
def f3():
     return [ bb+ii*dd for bb,ii,dd in izip(b,i,d) ]

def run(f, K):
     t0 = time ()
     for i in xrange (K):
	f()
     return time()-t0

T = 2000000

def BENCH(K):
     global b, i, d
     N = T/K
     print "%i times tuples of size %i:" % (K,N)
     b = tuple (range(0, -N, -1))
     i = tuple (range(N))
     d = tuple (N*[1])
     for x, y in sorted ([(run (x1,K), y1) for x1, y1 in 
((f1,'map'),(f2,'zip'),(f3,'izip'))]):
	print '%s: %.2f' %(y,x),
     print

BENCH(200000)
BENCH(20000)
BENCH(2000)
BENCH(200)
BENCH(20)
BENCH(1)
#--------------------------------------------------------

On 2.4.1 I get:

python zipmap.py
200000 times tuples of size 10:
izip: 1.32 zip: 1.50 map: 1.60
20000 times tuples of size 100:
izip: 1.00 zip: 1.14 map: 1.29
2000 times tuples of size 1000:
izip: 0.94 zip: 1.10 map: 1.28
200 times tuples of size 10000:
izip: 0.93 map: 1.29 zip: 1.51
20 times tuples of size 100000:
izip: 0.96 map: 1.31 zip: 2.28
1 times tuples of size 2000000:
izip: 0.96 map: 1.33 zip: 13.28



Stelios



More information about the Python-list mailing list