前言

Python代码想统计运行时间有很多种方法,这里介绍比较常用的2种方法。方法1,通过代码统计;方法2,通过Pycharm编辑器统计。

统计运行时间是很有意义的,可以比较不同的代码运行耗时,也可以比较不同的方案耗时从而选择效率更高的方案,等等。具体统计方法详见下文。

日期:2023年4月。

方法1(推荐):通过代码统计

说明

time.clock()函数在Python3.3被废弃了,并在Python3.8被移除,若在之后的Python版本中使用此函数,则会有以下警告或提示:

DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead time.clock()

解决方法在提示中也给出了,即使用time.perf_countertime.process_time函数作为替代,经本人测试,使用time.perf_counter函数与真实时间较为接近,因此推荐使用time.perf_counter函数。

步骤

  1. 导入time库:import time
  2. 代码开始前获取开始时间:start = time.perf_counter()
  3. 编写代码
  4. 代码结束后获取结束时间:end = time.perf_counter()
  5. 计算运行时间:runTime = end - start
  6. 输出运行时间:print("运行时间:", runTime)

单位

time.perf_counter()获取的时间单位为s,即秒。数值乘以1000则为毫秒。

完整示例

import time

# time.clock()默认单位为s
# 获取开始时间
start = time.perf_counter()
'''
代码开始
'''
sum = 0
for i in range(100):
    for j in range(100):
        sum = sum + i + j
print("sum = ", sum)
'''
代码结束
'''
# 获取结束时间
end = time.perf_counter()
# 计算运行时间
runTime = end - start
runTime_ms = runTime * 1000
# 输出运行时间
print("运行时间:", runTime, "秒")
print("运行时间:", runTime_ms, "毫秒")

运行结果

方法2:通过Pycharm编辑器

打开Pycharm编辑器,找到想要运行的脚本,点击Run - Profile 'YourScript',如图:
在这里插入图片描述

同样,点击PyCharm有右上角的带有时间标志的运行按钮也是一样的效果,如图:
在这里插入图片描述

随后便可得到分析结果,可查看运行时间,如图:
在这里插入图片描述

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐