python如何显示计算时间

python如何显示计算时间

作者:William Gu发布时间:2026-01-05阅读时长:0 分钟阅读次数:12

用户关注问题

Q
如何在Python中测量代码块的执行时间?

我想知道在Python中,怎样准确地测量某段代码的运行时间?有没有简单且高效的方法?

A

使用time模块的time()函数测量代码执行时间

可以使用Python的time模块中的time()函数,通过记录代码执行前后的时间差来计算执行时间。具体做法是先保存开始时间,执行代码块,然后保存结束时间,最后用结束时间减去开始时间获得运行时间。例如:

import time
start_time = time.time()
# 要测试的代码
end_time = time.time()
print(f"运行时间: {end_time - start_time}秒")
Q
Python中有没有更精确的时间测量方式?

使用time模块的time()函数有时不够精确,有什么其他方法能获得更高精度的计时结果吗?

A

使用time模块的perf_counter()函数提高计时精度

time模块中提供了perf_counter()函数,用来测量短时间间隔,精度比time()更高并且不会受到系统时间调整影响。使用方式类似,记录执行前后时间差即可。例如:

import time
start = time.perf_counter()
# 代码段
end = time.perf_counter()
print(f"代码运行时间: {end - start}秒")
Q
有没有更方便的方式在Python中测量函数的运行时间?

希望能直接装饰某个函数,自动打印或获取该函数的执行时间,有没有相关方法?

A

使用装饰器自动统计函数运行时间

可以编写一个装饰器函数,包裹需要测量时间的函数,实现自动输出执行时间的功能。例如:

def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        print(f"函数 {func.__name__} 运行时间: {end - start}秒")
        return result
    return wrapper

@timer
def example():
    pass

这样调用example()时会自动打印运行时长。