On Mon, Aug 1, 2011 at 7:51 PM, Noufal Ibrahim <nou...@gmail.com> wrote: > Anand Balachandran Pillai <abpil...@gmail.com> writes: > >> On Mon, Aug 1, 2011 at 6:08 AM, Anand Chitipothu <anandol...@gmail.com>wrote: > > [...] > >> It is more subtler than that. >> >> List comprehensions are faster than map functions when >> the latter needs to invoke a user-defined function call or a lambda. >> >> Maps score over list comprehensions in most cases where the function >> is a Python built-in and when no lambda is used. >> >> Example of former: >> >>>>> def f1(): map(sqr, range(1, 100)) >> ... >>>>> def f2(): [sqr(x) for x in range(1, 100)] >> ... >>>>> mytimeit.Timeit(f1) >> '37.91 usec/pass' >>>>> mytimeit.Timeit(f2) >> '37.50 usec/pass' >> >> Example of latter: >> >>>>> def f1(): map(hex, range(1, 100)) >> ... >>>>> def f2(): [hex(x) for x in range(1, 100)] >> ... >>>>> mytimeit.Timeit(f1) >> '49.41 usec/pass' >>>>> mytimeit.Timeit(f2) >> '55.29 usec/pass' > > This is confusing. Why is > > map(sqr, range(1, 100)) > > faster than > > map(hex, range(1, 100)) > > Assuming sqr is implemented in python, it should be slower than hex > which is implemented in C. Here's what I get (note: sqrt is faster than hex - not sqr)
Program ======= from math import sqrt from timeit import Timer def sqr(x) : x * x print "Simple sqr", Timer("sqr(50)","from __main__ import sqr").timeit() print "Simple sqrt", Timer("sqrt(50)","from math import sqrt").timeit() print "Simple hex", Timer("hex(50)").timeit() print "Map sqr", Timer("map(sqr,range(1,100))","from __main__ import sqr").timeit() print "Map sqrt", Timer("map(sqrt,range(1,100))","from math import sqrt").timeit() print "Map hex", Timer("map(hex,range(1,100))").timeit() Output ====== Simple sqr 0.185955047607 Simple sqrt 0.108409881592 Simple hex 0.143438816071 Map sqr 21.4051530361 Map sqrt 12.3786129951 Map hex 13.8608310223 _______________________________________________ BangPypers mailing list BangPypers@python.org http://mail.python.org/mailman/listinfo/bangpypers