'Timing in Python
I'm trying to learn more about how to build a time-efficient program in python. However, while I was trying to work with "timeit" module, I faced something confusing. Here is my piece of code:
import timeit
stmt='''
f1(100)
'''
setup='''
def f1(n):
return [str(num) for num in range(n)]
'''
print(timeit.timeit(stmt,setup,number=1000000))
stmt2='''
f2(100)
'''
setup2='''
def f2(n):
return list(map(str, [x for x in range(n)]))
'''
print(timeit.timeit(stmt2,setup2,number=1000000))
In most of the time f1 beats f2, but if I replace f2 function with the code below, f2 always beats f1 with a noticeable amount of time:
def f2(n):
return list(map(str, range(n)))
First, I'd like to know what's the reason? And then, if I again modify f2 function with lambda expression, it would have the least time-efficiency. So, why should we use lambda expression for other matters than passing it as an argument for another function?
def f2(n):
return list(map(lambda x:str(x),range(n)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
