[英]Why is timeit slower when called from a python file with map and a predefined function over being called via cli with map and a lambda expression?
I am checking whether lambda expressions are faster compared to predefined functions. 我正在检查lambda表达式与预定义函数相比是否更快。 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 如下将其更改为lambda表达式
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+. 速度大致相同,即〜3秒+。
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. 降低了将近一秒。
In your commandline version, you're creating the xs
list in your setup code, so it's creation is not getting timed. 在您的命令行版本中,您是在安装代码中创建xs
列表的,因此它的创建没有时间限制。 In the non-commandline version, xs
is created within test
which is the function being timed. 在非命令行版本中, xs
是在test
中创建的,它是要计时的函数。 Because of this, the two versions aren't timing the same thing. 因此,这两个版本的时机不同。
map(...)
命令行 :仅定时map(...)
list(10)
and map(...)
文件 :时间list(10)
和map(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.