面试题答案
一键面试安装 line_profiler 步骤
- 使用pip安装:打开命令行终端,运行以下命令:
pip install line_profiler
如果使用的是Python虚拟环境,确保虚拟环境已激活。若安装过程中权限不足,在Linux或macOS系统下可尝试使用sudo pip install line_profiler
,但不推荐长期使用sudo
安装包,尽量使用虚拟环境。在Windows系统下,可能需要以管理员身份运行命令提示符来安装。
使用 line_profiler 对 add_numbers
函数进行逐行性能分析
- 编写测试脚本:创建一个Python脚本,例如
test_add_numbers.py
,内容如下:
def add_numbers(a, b):
return a + b
if __name__ == '__main__':
result = add_numbers(3, 5)
print(result)
- 使用装饰器:修改脚本,使用
@profile
装饰器标记要分析的函数,修改后的脚本如下:
@profile
def add_numbers(a, b):
return a + b
if __name__ == '__main__':
result = add_numbers(3, 5)
print(result)
- 运行分析:在命令行终端中,进入脚本所在目录,运行以下命令:
kernprof -l -v test_add_numbers.py
-l
参数表示使用@profile
装饰器,-v
参数表示输出详细的分析结果。运行后,会看到类似如下的输出,展示函数每一行的执行时间等性能信息:
Wrote profile results to test_add_numbers.py.lprof
Timer unit: 1e-06 s
Total time: 2.2e-06 s
File: test_add_numbers.py
Function: add_numbers at line 1
Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 @profile
2 def add_numbers(a, b):
3 1 2.2 2.2 100.0 return a + b