简体   繁体   中英

using the map function with timeit in Python

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?

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

PS Probably not a good idea to use map for printing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM