使用 timeit 模块的 timer 类并设置 number=1 可以精准测试微秒级代码耗时。通过调用 time.perf_counter() 获取高精度时间戳,配合 timeit.repeat() 多次运行取最小值,能有效消除系统调度噪声。这种方法避免了 time.time() 的低精度问题,适合对性能敏感的单行或短代码片段测试。

如何配置 Timer 对象以获取单次执行时间?
配置 Timer 对象时,需传入待测代码字符串和初始化语句。设置 number=1 确保只执行一次,从而获得单次调用的真实耗时。返回的时间单位为秒,可转换为微秒以便阅读。此方法适用于评估函数调用开销或特定算法步骤的性能。

import timeit
def test_single_execution():
setup_code = "x = [i for i in range(100)]"
stmt_code = "sum(x)"
timer = timeit.Timer(stmt=stmt_code, setup=setup_code)
# number=1 表示只执行一次
elapsed = timer.timeit(number=1)
print(f"单次执行耗时: {elapsed * 1e6:.2f} 微秒")
test_single_execution()
为什么需要多次重复测试并取最小值?
由于操作系统调度、CPU 频率调节等因素,单次测量可能受噪声影响。通过
repeat()` 多次执行(如 10 次)并取最小值,能更接近代码的理论最低耗时。这反映了在无干扰情况下的最佳性能表现,是基准测试的标准做法。最小值通常对应于缓存命中且无上下文切换的理想状态。</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill13982" title="Nodriver 异步无检测 Chrome 浏览器自动化 Python"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20d3191a227.jpg" alt="Nodriver 异步无检测 Chrome 浏览器自动化 Python" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill13982" title="Nodriver 异步无检测 Chrome 浏览器自动化 Python">Nodriver 异步无检测 Chrome 浏览器自动化 Python</a>
<p>Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。</p>
</div>
<a href="/xiazai/skill13982" title="Nodriver 异步无检测 Chrome 浏览器自动化 Python" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><p><img src="https://img.php.cn/upload/article/000/969/633/179575237465867.png" alt="如何在Python中通过timeit精准测试微秒级代码耗时?"></p>
<pre class="brush:php;toolbar:false;">import timeit
def test_repeat_min():
setup_code = "x = [i for i in range(100)]"
stmt_code = "sum(x)"
timer = timeit.Timer(stmt=stmt_code, setup=setup_code)
# repeat 返回一个列表,包含每次运行的总时间
# number=1 确保每次只跑一次
results = timer.repeat(repeat=10, number=1)
min_time = min(results)
print(f"10次中最小耗时: {min_time * 1e6:.2f} 微秒")
print(f"所有结果: {[f'{r*1e6:.2f}' for r in results]}")
test_repeat_min()
当代码涉及全局变量时如何正确隔离作用域?
若待测代码依赖全局变量,应在 setup 参数中定义这些变量,或使用 <code>globals() 传递命名空间。直接在全局作用域引用可能导致意外共享状态。通过 setup 初始化局部变量,可确保每次测试环境一致,避免污染全局命名空间。这是保证测试结果可重复性的关键步骤。

















