gpt4 book ai didi

python - 具有随机列表的 timeit 函数

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:14 25 4
gpt4 key购买 nike

尝试计算对随机列表进行排序所需的时间:

import random
import timeit
randoms = random.sample(xrange(100), 10)

print randoms
timeit.timeit('sorted(r)',setup = 'r = random.sample(xrange(100), 10)')

错误:

Traceback (most recent call last):
File "C:/Users/Arthur/Desktop/Dropbox/uni stuff/cs/python/theory hmwk/random.py", line 6, in <module>
timeit.timeit('sorted(r)',setup = 'r = random.sample(xrange(100), 10)')
File "C:\Python27\lib\timeit.py", line 230, in timeit
return Timer(stmt, setup, timer).timeit(number)
File "C:\Python27\lib\timeit.py", line 195, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 3, in inner
NameError: global name 'random' is not defined

最佳答案

您需要在设置字符串中显式导入random:

timeit.timeit('sorted(r)',setup = 'import random; r = random.sample(xrange(100), 10)')
# ^^^^^^^^^^^^^

timeit.timeit 不会自动将名称拉入设置字符串,以避免意外扭曲测试结果(如果它导入了您不想要的名称怎么办?)

关于python - 具有随机列表的 timeit 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27005114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com