Python 逐行分析利器 line_profiler 使用 profile 装饰器逐行定位性能瓶颈 line_profiler 是一个第三方工具可以逐行统计每行代码的执行时间和调用次数。它能精确显示每个函数中哪一行最耗时是优化代码的关键工具。安装: pip install line_profilerimport timeimport random# 1. 基础示例使用 profile 装饰器 profiledef process_data(data: list) - list:逐行分析此函数以查找性能瓶颈。在终端通过 kernprof -l -v 运行本文件来激活分析。result []# 瓶颈通常出现在循环中for item in data:# 模拟耗时转换temp item * 2.5time.sleep(0.0001) # 模拟微小延迟transformed temp ** 2 tempresult.append(transformed)return result# 2. 字符串处理函数展示不同操作的耗时 profiledef string_operations(strings: list) - list:字符串拼接与处理逐行分析各种操作的开销。output []for s in strings:# 字符串拼接的多种方式upper_s s.upper()stripped upper_s.strip()reversed_s stripped[::-1]# 条件过滤if len(reversed_s) 5:output.append(reversed_s)else:output.append(stripped)return output# 3. 数学密集型运算分析 profiledef heavy_computation(n: int) - float:大量数学运算展示各行的计算耗时差异。total 0.0for i in range(n):# 不同数学运算的耗时不同sin_val __import__(math).sin(i)cos_val __import__(math).cos(i)combined sin_val ** 2 cos_val ** 2total combinedreturn total# 4. 多层函数调用时的逐行分析 def helper_sort(values: list) - list:辅助排序函数return sorted(values)def helper_filter(values: list) - list:辅助过滤函数return [v for v in values if v 0.5]profiledef pipeline_processing(size: int) - list:多层流水线处理分析各步骤耗时占比。# 第一步生成随机数据raw_data [random.random() for _ in range(size)]# 第二步数学变换transformed [x ** 2 3 * x - 1 for x in raw_data]# 第三步排序sorted_data helper_sort(transformed)# 第四步过滤result helper_filter(sorted_data)return result# 5. 文件读写操作分析 profiledef file_io_operations(filename: str, lines: list):文件读写 IO 操作的逐行耗时分析# 写入文件with open(filename, w, encodingutf-8) as f:for line in lines:f.write(line \n)# 读取文件with open(filename, r, encodingutf-8) as f:content f.readlines()# 统计行信息total_chars sum(len(line) for line in content)print(f总字符数: {total_chars})# 6. 手动使用 LineProfiler API def manual_line_profiler():不依赖装饰器手动创建 LineProfiler 进行分析from line_profiler import LineProfilerdef target_func():待分析的目标函数total 0for i in range(10000):total i ** 0.5return total# 手动创建并附加 profilerlp LineProfiler()lp.add_function(target_func)# 运行分析lp.enable()result target_func()lp.disable()# 打印逐行结果lp.print_stats()return result# 7. kernprof 命令行使用方式 使用 kernprof 运行 line_profiler 的两种方式:方式一直接运行并打印结果kernprof -l -v line_profiler_demo.py-l 表示使用逐行分析模式-v 表示运行完毕后立即打印结果方式二仅保存结果后续分析kernprof -l -o output.lprof line_profiler_demo.py查看 saved 文件:python -m line_profiler output.lprof输出字段含义:Line 代码行号Hits 该行被执行的次数Time 该行消耗的总时间微秒Per Hit 每次执行的平均时间% Time 在函数总时间中的占比Line Contents 源代码内容常用技巧:1. 重点分析循环体内代码循环外代码通常不是瓶颈2. 关注 % Time 最高的行它们是最值得优化的地方3. Per Hit 很高的行可能存在可以缓存的计算4. 函数调用行(python 内部调用)实际耗时会在子函数中体现# 主入口生成足够的测试数据 if __name__ __main__:print([INFO] 请使用 kernprof -l -v 本文件 运行以查看逐行分析结果)print([INFO] 当前代码已添加 profile 装饰器可直接用于分析)# 生成测试数据numbers list(range(100))texts [ hello world , python profiling , line profiler ] * 30# 调用各函数会被 profile 追踪process_data(numbers)string_operations(texts)heavy_computation(500)pipeline_processing(200)file_io_operations(_test_profile.txt, texts)
Python逐行分析line_profiler
Python 逐行分析利器 line_profiler 使用 profile 装饰器逐行定位性能瓶颈 line_profiler 是一个第三方工具可以逐行统计每行代码的执行时间和调用次数。它能精确显示每个函数中哪一行最耗时是优化代码的关键工具。安装: pip install line_profilerimport timeimport random# 1. 基础示例使用 profile 装饰器 profiledef process_data(data: list) - list:逐行分析此函数以查找性能瓶颈。在终端通过 kernprof -l -v 运行本文件来激活分析。result []# 瓶颈通常出现在循环中for item in data:# 模拟耗时转换temp item * 2.5time.sleep(0.0001) # 模拟微小延迟transformed temp ** 2 tempresult.append(transformed)return result# 2. 字符串处理函数展示不同操作的耗时 profiledef string_operations(strings: list) - list:字符串拼接与处理逐行分析各种操作的开销。output []for s in strings:# 字符串拼接的多种方式upper_s s.upper()stripped upper_s.strip()reversed_s stripped[::-1]# 条件过滤if len(reversed_s) 5:output.append(reversed_s)else:output.append(stripped)return output# 3. 数学密集型运算分析 profiledef heavy_computation(n: int) - float:大量数学运算展示各行的计算耗时差异。total 0.0for i in range(n):# 不同数学运算的耗时不同sin_val __import__(math).sin(i)cos_val __import__(math).cos(i)combined sin_val ** 2 cos_val ** 2total combinedreturn total# 4. 多层函数调用时的逐行分析 def helper_sort(values: list) - list:辅助排序函数return sorted(values)def helper_filter(values: list) - list:辅助过滤函数return [v for v in values if v 0.5]profiledef pipeline_processing(size: int) - list:多层流水线处理分析各步骤耗时占比。# 第一步生成随机数据raw_data [random.random() for _ in range(size)]# 第二步数学变换transformed [x ** 2 3 * x - 1 for x in raw_data]# 第三步排序sorted_data helper_sort(transformed)# 第四步过滤result helper_filter(sorted_data)return result# 5. 文件读写操作分析 profiledef file_io_operations(filename: str, lines: list):文件读写 IO 操作的逐行耗时分析# 写入文件with open(filename, w, encodingutf-8) as f:for line in lines:f.write(line \n)# 读取文件with open(filename, r, encodingutf-8) as f:content f.readlines()# 统计行信息total_chars sum(len(line) for line in content)print(f总字符数: {total_chars})# 6. 手动使用 LineProfiler API def manual_line_profiler():不依赖装饰器手动创建 LineProfiler 进行分析from line_profiler import LineProfilerdef target_func():待分析的目标函数total 0for i in range(10000):total i ** 0.5return total# 手动创建并附加 profilerlp LineProfiler()lp.add_function(target_func)# 运行分析lp.enable()result target_func()lp.disable()# 打印逐行结果lp.print_stats()return result# 7. kernprof 命令行使用方式 使用 kernprof 运行 line_profiler 的两种方式:方式一直接运行并打印结果kernprof -l -v line_profiler_demo.py-l 表示使用逐行分析模式-v 表示运行完毕后立即打印结果方式二仅保存结果后续分析kernprof -l -o output.lprof line_profiler_demo.py查看 saved 文件:python -m line_profiler output.lprof输出字段含义:Line 代码行号Hits 该行被执行的次数Time 该行消耗的总时间微秒Per Hit 每次执行的平均时间% Time 在函数总时间中的占比Line Contents 源代码内容常用技巧:1. 重点分析循环体内代码循环外代码通常不是瓶颈2. 关注 % Time 最高的行它们是最值得优化的地方3. Per Hit 很高的行可能存在可以缓存的计算4. 函数调用行(python 内部调用)实际耗时会在子函数中体现# 主入口生成足够的测试数据 if __name__ __main__:print([INFO] 请使用 kernprof -l -v 本文件 运行以查看逐行分析结果)print([INFO] 当前代码已添加 profile 装饰器可直接用于分析)# 生成测试数据numbers list(range(100))texts [ hello world , python profiling , line profiler ] * 30# 调用各函数会被 profile 追踪process_data(numbers)string_operations(texts)heavy_computation(500)pipeline_processing(200)file_io_operations(_test_profile.txt, texts)