普通方法(最慢):
import random li=[random.randint(0, 1000) for r in xrange(10000)]
利用random.sample(中等):
import random random.sample(range(10000), 10000)
利用numpy.random(最快):
import numpy.random as nprnd nprnd.randint(1000, size=10000)
测试结果如下:
import numpy.random as nprnd import timeit t1 = timeit.Timer('[random.randint(0, 1000) for r in xrange(10000)]', 'import random') # v1 t2 = timeit.Timer('random.sample(range(10000), 10000)', 'import random') # v2 t3 = timeit.Timer('nprnd.randint(1000, size=10000)', 'import numpy.random as nprnd') # v3 print t1.timeit(1000)/1000 print t2.timeit(1000)/1000 print t3.timeit(1000)/100
具体时间如下:
0.0131397729926 0.00475841206447 0.00055090731109