Reputation: 1162
I am checking whether lambda expressions are faster compared to predefined functions. Here is my code to test predefined function
import timeit
def ad(x):
return x + 2
def test():
xs = range(10)
map(ad, xs)
print timeit.timeit("test()", setup="from __main__ import ad, test")
Running it
python add.py
3.21725106239
Changed it to a lambda expression as follows
import timeit
def test():
xs = range(10)
map(lambda x: x+2, xs)
print timeit.timeit("test()", setup="from __main__ import test")
The speed is more or less the same, that is ~3 sec+.
However when I run from the command line the following code the results are as follows
➜ /tmp python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 2.42 usec per loop
That is nearly a second lower.
Upvotes: 0
Views: 30
Reputation: 310227
In your commandline version, you're creating the xs
list in your setup code, so it's creation is not getting timed. In the non-commandline version, xs
is created within test
which is the function being timed. Because of this, the two versions aren't timing the same thing.
map(...)
list(10)
and map(...)
Upvotes: 2