【发布时间】:2020-01-11 13:55:23
【问题描述】:
我正在尝试测量 Python 中 contains() 函数的性能。我通过使用python的时间模块来做到这一点。
代码如下:
from time import time
def contains(collection, target):
return target in collection
def performance():
n = 1024
while n < 50000000:
sorted = range(n)
now = time()
# code whose performance
#
# is to be evaluated
contains(sorted, -1)
done = time()
print(n, (done-now)*1000)
n *= 2
performance()
我遇到的问题是,即使我增加了小数位,我也总是观察到 0 时差。我缺少 time() 模块中的一些标志。我也在使用python 3.7。我应该说我的机器并没有那么快,可以在两行之间传递 0 时间。
这是输出:
1024 0.0
2048 0.0
4096 0.0
8192 0.0
16384 0.0
32768 0.0
65536 0.0
131072 0.0
262144 0.0
524288 0.0
1048576 0.0
2097152 0.0
4194304 0.0
8388608 0.0
16777216 0.0
33554432 0.0
Process finished with exit code 0
【问题讨论】:
-
in对于范围 afaik 来说非常快,因为它可以使用数学而不是线性检查来检查。考虑改用timeit。无论如何,您都会得到更准确的结果。 -
尝试获取时间差以连续运行 100 次而不是一次
-
@MohammadAthar
timeit会自动执行此操作。 -
@Erindy,有
ipython的经验吗?
标签: python arrays python-3.x time