带有随机列表的timeit函数 [英] timeit function with random list
本文介绍了带有随机列表的timeit函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试计时对随机列表进行排序所需的时间:
Trying to time how long it takes to sort a random list:
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
:
You need to explicitly import random
in the setup string:
timeit.timeit('sorted(r)',setup = 'import random; r = random.sample(xrange(100), 10)')
# ^^^^^^^^^^^^^
timeit.timeit
不会自动将名称拉到设置字符串中,以免意外歪曲测试结果(如果它导入了您不想要的名称该怎么办?)
timeit.timeit
does not automatically pull names into the setup string to avoid accidentally skewing the results of your tests (what if it imported a name that you did not want?)
这篇关于带有随机列表的timeit函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文