Python Time 库使用:计算代码运行时间
这段代码使用 Python 的 time 库来计算一段代码的运行时间。
import time
# 代码开始运行
start = time.perf_counter()
sum = 0
for i in range(100000000):
sum += i
print('sum = ', sum)
# 代码结束运行
end = time.perf_counter()
# 计算运行时间,单位为秒
print('计算一亿运行时间为:{}秒'.format(end-start))
这段代码没有输出乱码的问题,可能是在复制粘贴过程中出现了编码问题。请尝试重新复制代码,并确保粘贴到合适的编辑器或 IDE 中。
代码解析:
- 导入 time 库:
import time - 记录开始时间:
start = time.perf_counter() - 执行代码: 此处是一个计算 1 到 1 亿数字之和的循环,可以替换为您的实际代码
- 记录结束时间:
end = time.perf_counter() - 计算运行时间:
end - start - 输出结果:
print('计算一亿运行时间为:{}秒'.format(end-start))
注意事项:
- 确保您的代码在 Python 3 环境下运行。
time.perf_counter()函数返回的是高精度时间戳,适合用于计算代码运行时间。- 可以根据需要修改代码中的循环次数,以测试不同代码的运行时间。
原文地址: https://www.cveoy.top/t/topic/pdcm 著作权归作者所有。请勿转载和采集!