timeit function with random list

心不动则不痛 提交于 2019-12-13 18:34:06

问题


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)')

Error:

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

回答1:


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 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?)



来源:https://stackoverflow.com/questions/27005114/timeit-function-with-random-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!