英文:
Is there an easier or more efficient method to find the average running time of an algorithm?
问题
# 创建50个链表,每个链表包含2500个随机整数
for i in range(0, 50):
myList = LinkedList()
start = time.time()
for i in range(0, 2500):
myList.append(randint(0, 9))
end = time.time()
runtime = end - start
runtimes = []
runtimes.append(runtime)
for i in range(len(runtimes)):
average = 0
average += runtime
average /= len(runtimes)
print(average) # 10秒
# 想知道是否有更好的方法来计算平均值,而不是将每个运行时间添加到一个列表中,循环遍历运行时间列表,将每个运行时间添加到“average”,然后除以运行时间列表的长度。
英文:
# create 50 linked list with 2500 random integers
for i in range(0, 50):
myList = LinkedList()
start = time.time()
for i in range(0, 2500):
myList.append(randint(0, 9))
end = time.time()
runtime = end - start
runtimes = []
runtimes.append(runtime)
for i in range(len(runtimes)):
average = 0
average += runtime
average /= len(runtimes)
print(average) # 10s
Wondering if there's a better method to find the average instead of adding each run time to a list, looping through the list of runtimes, adding each runtime to average
, then dividing by the length of the list of runtimes.
答案1
得分: 1
是的
import timeit
ttl = timeit.timeit(lambda: alist.append(5),number=2500)
print(f"花费了 {ttl} ... 平均值: {ttl/2500}")
或者甚至是 sum(runtimes)/len(runtimes)
英文:
yes
import timeit
ttl = timeit.timeit(lambda: alist.append(5),number=2500)
print(f"Took {ttl} ... avg: {ttl/2500}")
or even really sum(runtimes)/len(runtimes)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论