这是一个优惠券收集器代码,用于分析运行时间。我需要一些关于如何提高这段代码的运行时间的建议?我使用过数据结构字典,但是有没有其他的数据结构可以更快地执行呢。在
import random
import numpy as np
import matplotlib.pyplot as plt
from array import *
import timeit
trailList = {}
def couponcollector(n):
numDic = {}
trails = 0
while len(numDic) < n:
num = np.random.random_integers(n);
trails = trails + 1
if num not in numDic.keys():
numDic[num] = 1
return trails
def starter(n,m):
summ = 0
for i in range(0,m):
r = couponcollector(n)
summ = summ + r
if trailList.has_key(r):
trailList[r] = trailList[r] + 1
else:
trailList[r] = 1
print trailList
#print "Expected Trails"
#print summ/300
nvalues= []
runtimes = []
runtimes1 = []
runtimes2 = []
runtimes3 = []
runtimes4 = []
#color = {300: 'blue', 1000: 'green', 5000: 'red', 10000: 'black'}
def runtimer():
for n in range(300,20000,4000):
nvalues.append(n)
#stmt = 'starter(' + str(n)+','+str(300) + ')'
#stmt1 = 'starter(' + str(n)+','+str(800) + ')'
stmt2 = 'starter(' + str(n)+','+str(1000) + ')'
stmt3 = 'starter(' + str(n)+','+str(3000) + ')'
stmt4= 'starter(' + str(n)+','+str(5000) + ')'
print(nvalues)
#runtimes.append(timeit.timeit(stmt, setup="from __main__ import starter", number = 1))
#runtimes1.append(timeit.timeit(stmt1, setup="from __main__ import starter", number = 1))
runtimes2.append(timeit.timeit(stmt2, setup="from __main__ import starter", number = 1))
print runtimes2
runtimes3.append(timeit.timeit(stmt3, setup="from __main__ import starter", number = 1))
runtimes4.append(timeit.timeit(stmt4, setup="from __main__ import starter", number = 1))
fig = plt.figure()
#plt.plot(nvalues, runtimes, c='blue', label='m = 300')
#plt.plot(nvalues, runtimes1, c='green', label='m = 800')
plt.plot(nvalues, runtimes2, c='red', label='m = 1000')
plt.plot(nvalues, runtimes3, c='blue', label='m = 3000')
plt.plot(nvalues, runtimes4, c='green', label='m = 5000')
plt.ylabel('Runtimes')
plt.xlabel('Coupon Collector Domain Size')
plt.title('Plot of Coupon Collector runtimes')
plt.legend(loc='upper left')
plt.grid(True)
fig.savefig('ccFinal.png')
runtimer()
目前没有回答
相关问题 更多 >
编程相关推荐