Dijkstra on Python
gbreed at cix.compulink.co.uk
gbreed at cix.compulink.co.uk
Fri Aug 16 05:12:28 EDT 2002
James J. Besemer wrote:
> I mean this strikes me as crazy. People are saying get rid of lambda
> and map when they're typically faster than for or while loops and
> then they praise comprehensions when they're the most unusual
> and slowest of all.
Well, I suppose that could be because Python programmers aren't that
bothered about the speed of their language constructs. That's why they
keep on programming in Python. Another reason is that what you say isn't
true:-
Python 2.2 (#1, Dec 31 2001, 15:21:18)
[GCC 2.95.3-5 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> def byComprehension(n):
... stamp = time.time()
... [x*x for x in range(n)]
... return time.time()-stamp
...
>>> def byLambda(n):
... stamp = time.time()
... map(lambda x: x*x, range(n))
... return time.time()-stamp
...
>>> def byFor(n):
... stamp = time.time()
... result = []
... for x in range(n):
... result.append(x*x)
... return time.time()-stamp
...
>>> byComprehension(10000)
0.014999985694885254
>>> byLambda(10000)
0.016000032424926758
>>> byFor(10000)
0.014999985694885254
>>> byComprehension(10000)
0.014999985694885254
>>> byComprehension(100000)
3.406000018119812
>>> byLambda(100000)
3.4839999675750732
>>> byFor(100000)
3.437000036239624
>>> byComprehension(100000)
3.406999945640564
>>> byComprehension(1000000)
59.562999963760376
>>> byLambda(1000000)
60.422000050544739
>>> byFor(1000000)
59.187999963760376
>>> byComprehension(1000000)
58.827999949455261
>>> total = 0.0
>>> for each in xrange(10000):
... total += byComprehension(100)
...
>>> total
1.7340000867843628
>>> total = 0.0
>>> for each in xrange(10000):
... total += byLambda(100)
...
>>> total
1.7500002384185791
>>> total = 0.0
>>> for each in xrange(10000):
... total += byFor(100)
...
>>> total
2.4679998159408569
>>> total = 0.0
>>> for each in xrange(10000):
... total += byComprehension(100)
...
>>> total
1.685999870300293
>>>
Graham
More information about the Python-list
mailing list