使用time.perf_counter()可进行高精度简单计时;2. 使用timeit模块能更精确测量代码段执行时间,适合性能比较;3. 避免测量开销、系统干扰、jit/缓存效应、i/o影响和未热启动等误区;4. 进阶性能分析可借助cprofile、snakeviz、line_profiler和memory_profiler等工具实现函数级、行级及内存使用深度分析,从而精准定位性能瓶颈并优化。

Python提供了多种方法来统计脚本的执行时间,最常用且基础的,无非就是利用内置的
time
timeit
要统计Python脚本或代码段的执行时间,我们通常会用到以下几种方式。
1. 使用 time
立即学习“Python免费学习笔记(深入)”;
这是最直接的方法,通过记录代码执行前后的时间戳,然后计算差值。我个人最常用的是
time.perf_counter()
time.time()
import time
def my_slow_function():
"""一个模拟耗时操作的函数"""
sum_val = 0
for i in range(10000000):
sum_val += i * i
return sum_val
# 记录开始时间
start_time = time.perf_counter()
# 执行你的脚本或代码段
result = my_slow_function()
# 记录结束时间
end_time = time.perf_counter()
# 计算并打印执行时间
execution_time = end_time - start_time
print(f"函数执行结果: {result}")
print(f"脚本执行时间: {execution_time:.6f} 秒")
# 如果想用time.time(),原理一样
# start_time_wall = time.time()
# my_slow_function()
# end_time_wall = time.time()
# print(f"脚本执行时间 (time.time): {end_time_wall - start_time_wall:.6f} 秒")2. 使用 timeit
timeit
你可以直接在Python脚本中使用
timeit.timeit()
import timeit
# 定义要测试的代码字符串
code_to_test = """
sum_val = 0
for i in range(10000000):
sum_val += i * i
"""
# 定义设置代码字符串(例如导入模块或定义函数)
setup_code = """
# 如果my_slow_function定义在外部,需要在这里导入
# from __main__ import my_slow_function
"""
# 执行计时,默认运行1,000,000次,这里为了快点,我们设置少一点
# number 参数指定了每个循环中代码执行的次数
# repeat 参数指定了计时器重复运行整个测试的次数
# timeit.timeit(stmt, setup, timer, number)
# timeit.repeat(stmt, setup, timer, repeat, number)
times = timeit.repeat(stmt=code_to_test, setup=setup_code, number=1, repeat=5)
print(f"代码执行时间 (重复5次,每次执行1次): {min(times):.6f} 秒 (最短时间)")
print(f"所有执行时间: {[f'{t:.6f}' for t in times]}")
# 如果要测试一个函数,可以这样写
def another_slow_function():
return sum(range(10000000))
# 注意 setup='from __main__ import another_slow_function'
# 这样 timeit 才能找到这个函数
function_times = timeit.repeat(
stmt='another_slow_function()',
setup='from __main__ import another_slow_function',
number=1,
repeat=5
)
print(f"函数 another_slow_function 执行时间: {min(function_times):.6f} 秒 (最短时间)")更棒的是,
timeit
# 在命令行中直接运行,测试一段代码 python -m timeit "'-'.join(str(n) for n in range(100))" # 测试一段更长的代码,可以写成多行 python -m timeit -s "import math" "math.sqrt(2)" # 测试一个函数(需要确保函数在当前环境中可用,或在setup中导入) # 假设你的脚本叫 my_script.py 里面有 my_slow_function # python -m timeit -s "from my_script import my_slow_function" "my_slow_function()"
通过命令行使用
timeit
说实话,刚开始写代码的时候,我可能没那么在意执行时间。但随着项目复杂度提升,你会发现,那些看似微不足道的毫秒,累积起来就是实实在在的用户等待,或者是服务器上不必要的资源消耗。精确计时,首先是帮你找到代码里的“慢动作”,那些拖后腿的瓶颈。比如你写了一个数据处理脚本,跑了半天没结果,这时候不计时,你怎么知道是算法问题还是IO阻塞?其次,它还是个衡量不同方案优劣的尺子。同一功能,A方案跑了10秒,B方案只用了1秒,高下立判。这不仅关乎用户体验,也直接影响服务器资源消耗和运营成本。所以,这不仅仅是技术细节,更是效率和成本的考量。它能帮助我们做出数据驱动的优化决策,而不是凭感觉猜测。
计时这事儿,看起来简单,但要做到精确且有意义,里头门道还真不少。我踩过不少坑,也总结了一些经验。
time.time()
time.time()
timeit
timeit
如果你的脚本执行时间确实很长,而且基础计时已经告诉你“这里有问题”,但具体是哪一行、哪个函数拖了后腿,这时候就需要更专业的工具了。
cProfile
profile
cProfile
profile
import cProfile
import pstats
def another_complex_function():
total = 0
for i in range(1000000):
total += i * i
return total
def main_logic():
another_complex_function()
time.sleep(0.1) # 模拟一些I/O等待
list_comp = [x*x for x in range(500000)]
return list_comp
profiler = cProfile.Profile()
profiler.enable() # 开启性能分析
main_logic() # 运行你的代码
profiler.disable() # 关闭性能分析
# 打印分析结果
stats = pstats.Stats(profiler).sort_stats('cumulative') # 按累积时间排序
stats.print_stats(10) # 打印前10行
# stats.dump_stats('profile_results.prof') # 保存结果到文件cProfile
snakeviz
snakeviz
cProfile
snakeviz profile_results.prof
line_profiler
line_profiler
pip install line_profiler
memory_profiler
memory_profiler
这些工具虽然不像
time
以上就是Python命令怎样统计脚本的执行时间 Python命令计时功能的基础教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号