possibly trivial newbie list/array question
Alex Martelli
aleax at aleax.it
Wed Aug 22 05:19:31 EDT 2001
"Sylvain Thenault" <syt at pegasus.logilab.fr> wrote in message
news:slrn9o6qhq.11k.syt at pegasus.logilab.fr...
...
> >IMHO, the faster way to do it consists in using builtin map function:
> >
> >map([1.0, 2.0, 3.0], lambda x: 4.0*x)
> >
> oops, this is better:
> map(lambda x: x*4.0, [1.0, 2.0, 3.0])
Why opine when you can measure?
mul.py:
import time
start = time.clock()
for i in range(10000):
junk = map(lambda x: 4.0*x, [1.0, 2.0, 3.0])
stend = time.clock()
print "%.2f"%(stend-start)
start = time.clock()
for i in range(10000):
junk = [4.0*x for x in [1.0, 2.0, 3.0]]
stend = time.clock()
print "%.2f"%(stend-start)
[repeated another time to avoid cache effects]
On my trusty old box:
D:\py21>python -OO mul.py
0.34
0.31
0.34
0.31
D:\py21>python -OO mul.py
0.34
0.31
0.34
0.31
D:\py21>python -OO mul.py
0.33
0.31
0.34
0.31
So, the nifty list-comprehension is at least as
fast as the map+lambda combo, and presumably a
bit faster, about 10% -- at least on this box
(Python 2.1.1, WinNT4, Pentium3-300, lots of RAM).
Alex
More information about the Python-list
mailing list