Reputation: 355
I am learning python and am looking at the difference in performance between using comprehension and the map function.
So far, I have this code:
import timeit
print timeit.timeit('[x for x in range(100)]',number = 10000)
def mapFunc(i):
print i
print timeit.timeit('map(mapFunc,range(100))',number = 10000)
After trying this, I have managed to get the list comprehension method to work correctly using timeit, however, I would like to compare this to the map function. When doing this, I get the error that mapFunc is not defined, and I do not know how to fix this issue. Can someone please help?
Upvotes: 0
Views: 251
Reputation: 78554
You should setup the function definition via the setup
argument:
>>> setup='def mapFunc(): print(i)'
>>> timeit.timeit('map(mapFunc,range(100))', number=10000, setup=setup)
See the timeit
doc reference
P.S. Probably not a good idea to use map
for printing.
Upvotes: 2