如何用timeit为执行pytest的Python测试文件计时?
问题
想要使用timeit工具为执行pytest测试的Python文件计时,但多次尝试均失败。相关细节如下:
测试文件内容(unit_tests.py)
import pytest retcode: int | pytest.ExitCode = pytest.main() if retcode == pytest.ExitCode.OK: print(f"\n---\nAll good\n---\n")
尝试过的命令(均无效)
python -m timeit unit_tests.py- 给文件名加引号、去掉扩展名的组合
报错信息
Traceback (most recent call last): File "C:\Users\lhott\AppData\Local\Programs\Python\Python311\Lib\timeit.py", line 326, in main number, _ = t.autorange(callback) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lhott\AppData\Local\Programs\Python\Python311\Lib\timeit.py", line 224, in autorange time_taken = self.timeit(number) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\lhott\AppData\Local\Programs\Python\Python311\Lib\timeit.py", line 178, in timeit timing = self.inner(it, self.timer) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<timeit-src>", line 6, in inner unit_tests.py ^^^^^^^^^^^^^^ NameError: name 'unit_tests' is not defined
直接执行python unit_tests.py可正常运行,目录路径正确。
解决方案
错误原因是timeit会将传入的unit_tests.py当作Python代码片段执行,而非运行文件本身,因此它把unit_tests.py解析成了变量名,导致NameError。以下是两种可行的解决方式:
方式一:通过exec执行文件内容
使用timeit的-c参数,通过exec读取并执行文件内容,命令如下:
python -m timeit -c "exec(open('unit_tests.py').read())"
如果只想运行一次测试并计时(避免timeit默认的多次重复执行),可以添加-n 1 -r 1参数:
python -m timeit -n 1 -r 1 -c "exec(open('unit_tests.py').read())"
方式二:封装逻辑为函数后导入调用
先修改unit_tests.py,将测试执行逻辑封装成函数:
import pytest def run_tests(): retcode: int | pytest.ExitCode = pytest.main() if retcode == pytest.ExitCode.OK: print(f"\n---\nAll good\n---\n") if __name__ == "__main__": run_tests()
然后用timeit导入模块并调用函数:
python -m timeit -c "import unit_tests; unit_tests.run_tests()"
同样,若需单次计时,添加-n 1 -r 1参数即可。
内容的提问来源于stack exchange,提问作者FluidMechanics Potential Flows
相关产品推荐
相关产品推荐

