Python案例如何统计程序运行耗时?

wen python案例 79

本文目录导读:

Python案例如何统计程序运行耗时?

  1. 方法一:使用 time.time()(基础版)
  2. 方法二:使用 time.perf_counter()(推荐,精度更高)
  3. 方法三:使用 timeit 模块(适合精确测试小段代码)
  4. 方法四:使用装饰器(代码简洁,方便复用)
  5. 方法五:用 datetime 模块(适合较长任务)
  6. 实战对比建议

在Python中统计程序运行耗时,最常用的方法有多种,这里给你几个典型的案例:

使用 time.time()(基础版)

import time
# 记录开始时间
start_time = time.time()
# 这里是你要测试的代码
total = 0
for i in range(1000000):
    total += i
# 记录结束时间
end_time = time.time()
# 计算耗时(单位:秒)
elapsed_time = end_time - start_time
print(f"程序运行耗时:{elapsed_time:.6f} 秒")

输出示例:

程序运行耗时:0.087654 秒

使用 time.perf_counter()(推荐,精度更高)

time.perf_counter() 适用于测量短时间间隔,精度比 time.time() 更高:

import time
start_time = time.perf_counter()
# 测试代码
for i in range(500000):
    _ = i ** 2
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"程序运行耗时:{elapsed_time:.6f} 秒")

使用 timeit 模块(适合精确测试小段代码)

timeit 会避开垃圾回收等干扰,专门用于精确测量代码执行时间:

import timeit
# 定义要测试的代码(作为字符串)
code = """
total = 0
for i in range(1000000):
    total += i
"""
# 执行 1 次,返回耗时(秒)
elapsed_time = timeit.timeit(code, number=1)
print(f"运行耗时:{elapsed_time:.6f} 秒")

多次执行取平均值:

elapsed_time = timeit.timeit(code, number=10)  # 执行10次
print(f"平均耗时:{elapsed_time / 10:.6f} 秒")

使用装饰器(代码简洁,方便复用)

import time
from functools import wraps
def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        result = func(*args, **kwargs)
        end_time = time.perf_counter()
        print(f"函数 {func.__name__} 运行耗时:{end_time - start_time:.6f} 秒")
        return result
    return wrapper
@timer
def my_function():
    total = 0
    for i in range(1000000):
        total += i
    return total
# 调用函数时会自动打印耗时
result = my_function()

datetime 模块(适合较长任务)

from datetime import datetime
start_time = datetime.now()
# 你的代码
total = 0
for i in range(10000000):
    total += i
end_time = datetime.now()
elapsed_time = end_time - start_time
print(f"程序运行耗时:{elapsed_time}")  # 显示为 时:分:秒.微秒

实战对比建议

方法 适用场景 精度
time.time() 简单统计,误差可接受 秒级
time.perf_counter() 精确测量短时间任务 纳秒级
timeit 代码片段性能测试 最高
装饰器 多次测试不同函数 中等
datetime 长时间运行的任务 毫秒级

推荐使用: 日常开发最常用 time.perf_counter(),它不受系统时间调整影响,精度也足够。

如果还有其他问题,欢迎继续问我!

抱歉,评论功能暂时关闭!