有没有更简单或更有效的方法来找到算法的平均运行时间?

huangapple go评论78阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年7月13日 10:36:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76675545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定