使用time.time()适合简单计时,通过前后时间戳相减得耗时;timeit模块可进行高精度测试,执行多次取平均值更准确;装饰器方式能自动监控多个函数运行时间,提升代码复用性。

在 Python 开发中,计算函数运行时间常用的方法是使用 time 模块或 timeit 模块。选择哪种方式取决于你的需求:简单测试用 time.time(),精确测量建议用 timeit。
适用于快速查看函数执行耗时,代码简单直观。
import time <p>def my_function():</p><h1>模拟一些操作</h1><pre class='brush:python;toolbar:false;'>sum(i for i in range(100000))
start = time.time() my_function() end = time.time()
print(f"函数运行时间: {end - start:.4f} 秒")
立即学习“Python免费学习笔记(深入)”;
说明: time.time() 返回当前时间的时间戳(单位:秒),通过前后相减得到间隔。适合一次性调用的场景。
用于需要更高精度的性能测试,尤其适合对比不同实现方式的效率。
import timeit
<p>def my_function():
sum(i for i in range(100000))</p><h1>单次运行时间</h1><p>time_taken = timeit.timeit(my_function, number=1000)
print(f"运行 1000 次平均耗时: {time_taken:.6f} 秒")</p>说明: timeit.timeit(func, number=N) 会执行函数 N 次并返回总耗时,常用于排除系统波动影响,获得更稳定的结果。
如果多个函数都需要计时,可以封装成装饰器,提升代码复用性。
import time
from functools import wraps
<p>def timer(func):
@wraps(func)
def wrapper(*args, *<em>kwargs):
start = time.time()
result = func(</em>args, **kwargs)
end = time.time()
print(f"{func.<strong>name</strong>} 执行耗时: {end - start:.4f} 秒")
return result
return wrapper</p><p>@timer
def my_function():
sum(i for i in range(100000))</p><p>my_function() # 输出函数执行时间</p>说明: 装饰器方式无需修改原函数逻辑,只需添加 @timer 即可自动打印运行时间,适合开发调试阶段。
基本上就这些。日常调试用 time.time() 最快上手,做性能优化推荐 timeit,想批量监控函数可以用装饰器。不复杂但容易忽略细节,比如多次运行取平均值才更准确。
以上就是如何在python开发时计算函数运行时间?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号