Just wondering

Dave Angel davea at ieee.org
Fri May 15 19:54:40 EDT 2009


norseman wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Marco 
> Mariani wrote:
>> Gediminas Kregzde wrote:
>>
>>
>>> def doit(i):
>>>    pass
>>>
>>> def main():
>>>    a = [0] * 10000000
>>>    t = time()
>>>    map(doit, a)
>>>    print "map time: " + str(time() - t)
>>
>> Here you are calling a function ten million times, build a list with 
>> of ten million None results, then throw it away.
>>
>>
>>> def main2():
>>>    t = time()
>>>    a = [0] * 10000000
>>>    for i in a:
>>>        pass
>>>    print "loop time: " + str(time() - t)
>>
>> Here you do nothing but iterating 'i' over the 'a' list.
>>
>>
>>> main()  # takes approximately 5x times longer than main2()
>>> main2()
>>>
>>> I'm wondering were is catch?
>>
>> Function calls are not free in python. They cost a lot more than they 
>> do in C, Delphi or other languages.
>>
>
> Gediminas - You did a good job of testing the overhead.  All good 
> programmers do that!
>
> Steve
>
>
If the task is to test the overhead, then the two loops need to be 
equivalent.  The OP's conclusion, confirmed by many of you, is that 
map() is lots slower than for.  But if you add in the call overhead in 
the for loop, they come out within 2 percent.  If you just want to 
compare map() time to for time, use functions:

from time import time
def doit(i):
   pass
def main():
   a = [0] * 10000000
   t = time()
   map(doit, a)
   print "map time: " + str(time() - t)

def main2():
   a = [0] * 10000000
   t = time()
   for i in a:
       doit(i)
   print "loop time: " + str(time() - t)


main()
main2()

gives:
map time: 4.875
loop time: 4.79600000381




More information about the Python-list mailing list