LAMBDA IS IT USELESS?
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu Jul 12 04:45:27 EDT 2001
"Tomasz Lisowski" <lisowski.tomasz at sssa.NOSPAM.com.pl> wrote in
news:9ijk8l$jo6$1 at news.tpi.pl:
> Code 1 uses a builtin reduce function (fast), but nevertheless lambda
> function gets called for each element in some_list.
> Code 2 uses slower, native Python loop, but does not use any function
> calls
>
> Question: which version is better from performance point of view?
>
Well, one my system, using my arbitrary choice of parameters, and including
a third version which uses operator.__mul__, Code 1 loses big time every
time, code 2 wins slightly on short lists and code 3 just beats 2 on longer
lists. YMMV.
In real life of course, the for loop wins hands down almost every time as
it also takes less time to think about and write, and you'll have to run it
a lot to make up for that.
The code I used:
import time
def code1(some_list):
res = reduce(lambda x, y: x*y, some_list)
def code2(some_list):
res = 1.0
for x in some_list: res *= x
import operator
def code3(some_list, op=operator.__mul__):
res = reduce(op, some_list)
def timetest(loop, function, *args):
start = time.time()
for i in range(loop):
res = function(*args)
end = time.time()
print "%d calls to %s took %.2f seconds, %.2fmS/call" % (
loop, function.__name__,
(end-start), ((end-start)*1000)/loop)
if __name__=='__main__':
shortlist = [2.0]*8
longlist = [1.0]*10000
timetest(10000, code1, shortlist)
timetest(10000, code2, shortlist)
timetest(10000, code3, shortlist)
timetest(1000, code1, longlist)
timetest(1000, code2, longlist)
timetest(1000, code3, longlist)
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list