kernprof用于收集性能数据,而line_profiler用于分析结果。 基本用法 line_profiler的使用方法非常优雅。只需要用@profile装饰器标记要分析的函数: 1 2 3 4 5 6 7 8 9 10 11 12 13 from line_profiler.explicit_profiler import profile @profile def slow_function(): result = [] for i in range(10000):...
# 1 使用runcalllp.runcall(my_function)# 2. 创建wrapperlp_wrapper = lp(other_function) lp_wrapper() 最后,使用lp.print_stats()方法打印分析结果: lp.print_stats() 使用装饰器 如果你喜欢更简洁的方法,可以使用line_profiler提供的装饰器。 使用@profile装饰器来标记你想要分析性能的函数: fromline_prof...
lp.runcall(my_function) # 2. 创建wrapper lp_wrapper = lp(other_function) lp_wrapper() 最后,使用lp.print_stats()方法打印分析结果: lp.print_stats() 使用装饰器 如果你喜欢更简洁的方法,可以使用line_profiler提供的装饰器。 使用@profile装饰器来标记你想要分析性能的函数: from line_profiler import ...
py.lprof Timer unit: 1e-06 s Total time: 0.022633 s File: line_profiler_test.py Function: test_profiler at line 5 Line # Hits Time Per Hit % Time Line Contents === 5 @profile 6 def test_profiler(): 7 101 40.0 0.4 0.2 for i in range(100): 8 100 332.0 3.3 1.5 a = np...
pip install line_profiler AI代码助手复制代码 使用方法一:kernprof @profiledeffib(n):# 文件名aaa.pya, b =0,1foriinrange(0, n): a, b = b, a+breturna fib(5) AI代码助手复制代码 终端:kernprof -l -v aaa.py# -l表示逐行分析 -v用于控制台输出, 不加-v会把分析结果写入aaa.py.lprof文...
lp = LineProfiler() lp.add_function(do_one_stuff) lp.add_function(do_other_stuff) lp_wrapper = lp(do_stuff) lp_wrapper(numbers) lp.print_stats() 此时的输出结果如下图,可以看到每个被添加的函数都会显示该函数内每行代码执行时间: (引入其他文件的函数时,与使用本文件中定义的函数同理,详见下一...
example_function(1000000) 输出示例: example_function ran in: 0.12345 secs2.2 使用functools.wraps保持元信息 直接应用上述装饰器会丢失被装饰函数的一些重要属性,比如函数名、文档字符串等。为了解决这个问题,可以使用functools.wraps来保留这些元数据: from functools import wraps ...
在需要调试优化的代码中引用line_profiler 让我们直接来看一个案例: # line_profiler_test.py fromline_profilerimportLineProfiler importnumpyasnp @profile deftest_profiler(): foriinrange(100): a=np.random.randn(100) b=np.random.randn(1000) ...
Function: foo at line 1 Line # Hits Time Per Hit % Time Line Contents === 1 @profile 2 def foo(): 3 1 1.0 1.0 0.0 task = [] 4 5 102 47.0 0.5 0.5 for a in range(0, 101): 6 10302 4741.0 0.5 48.1 for b in range(0, 101): 7 10201 4975.0 0.5 50.5 if a +...
使用cProfile和line_profiler分析和优化Python程序性能: python 复制代码 import cProfile def test_func(): for i in range(1000000): pass cProfile.run('test_func()') 42. 持续集成与交付 使用Jenkins或GitHub Actions进行持续集成和交付: yaml