python性能分析器:line_profiler 代码: importline_profiler importsys deftest(): foriinrange(0,10): print( i**2) print("End of the function") prof = line_profiler.LineProfiler(test)#pass in the function to profile prof.enable()#start profiling test() prof.disable()#stop profiling prof.d...
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):...
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...
(numbers) do_one_stuff(numbers) do_other_stuff(numbers) if __name__=='__main__': numbers = [random.randint(1,100) for i in range(1000)] lp = LineProfiler() lp.add_function(do_one_stuff) lp.add_function(do_other_stuff) lp_wrapper = lp(do_stuff) lp_wrapper(numbers) lp....
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 +...
在需要调试优化的代码中引用line_profiler 让我们直接来看一个案例: # line_profiler_test.py fromline_profilerimportLineProfiler importnumpyasnp @profile deftest_profiler(): foriinrange(100): a=np.random.randn(100) b=np.random.randn(1000) ...
example_function(1000000) 输出示例: example_function ran in: 0.12345 secs2.2 使用functools.wraps保持元信息 直接应用上述装饰器会丢失被装饰函数的一些重要属性,比如函数名、文档字符串等。为了解决这个问题,可以使用functools.wraps来保留这些元数据: from functools import wraps ...
使用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
$ python -m line_profiler script_to_profile.py.lprof For example, here are the results of profiling a single function from a decorated version of the pystone.py benchmark (the first two lines are output from pystone.py, not kernprof): ...