如何更简便高效地计算算法的平均运行时间?
优化链表append操作平均运行时间的计算方法
你的原代码存在两处关键问题:
runtimes = []放在外层循环内部,导致每次循环都会重置列表,永远只能存储当前一次的运行时间,无法累积50次测试数据- 手动遍历列表计算平均的逻辑完全多余,因为列表中始终只有一个元素,输出的只是单次运行时间而非平均值
下面是更简便高效的优化方案:
1. 简化平均计算逻辑
不需要手动遍历累加,直接使用Python内置的sum()和len()函数即可。这两个函数是底层优化实现的,比手动循环的效率更高、代码更简洁。
2. 修正后的完整代码
将列表初始化移到外层循环外,同时避免重复使用循环变量,提升代码可读性:
import time from random import randint # 初始化列表存储所有运行时间,放在外层循环外 runtimes = [] # 外层循环用j,避免和内层循环的i冲突 for j in range(50): myList = LinkedList() start = time.perf_counter() # 用perf_counter()更适合短时间测量,精度更高 for i in range(2500): myList.append(randint(0, 9)) end = time.perf_counter() runtimes.append(end - start) # 直接计算并输出平均运行时间 average_runtime = sum(runtimes) / len(runtimes) print(f"平均运行时间: {average_runtime} 秒")
3. 内存优化版(无需存储所有运行时间)
如果只需要平均值,甚至可以不用维护列表,直接累加总运行时间,最后除以测试次数,能节省内存开销(尤其适合测试次数极多的场景):
import time from random import randint total_runtime = 0 test_count = 50 for j in range(test_count): myList = LinkedList() start = time.perf_counter() for i in range(2500): myList.append(randint(0, 9)) end = time.perf_counter() total_runtime += end - start average_runtime = total_runtime / test_count print(f"平均运行时间: {average_runtime} 秒")
额外优化提示
- 用
time.perf_counter()替代time.time():前者专门用于测量短时间间隔,精度更高,且不受系统时间调整的影响 - 避免重复定义变量:原代码中每次循环都重新定义
average,属于冗余操作
内容的提问来源于stack exchange,提问作者DMOSnd
相关产品推荐
相关产品推荐

