调试和分析在Python开发中发挥着重要做用。 调试器可帮助程序员分析完整的代码。 调试器设置断点,而剖析器运行咱们的代码,并给咱们执行时间的详细信息。 分析器将识别程序中的瓶颈。咱们将了解pdb Python调试器,cProfile模块和timeit模块来计算Python代码的执行时间。python
涉及内容:程序员
trace_example.pyapp
class Student: def __init__(self, std): self.count = std def go(self): for i in range(self.count): print(i) return if __name__ == '__main__': Student(5).go()
执行:函数
$ python3 -m trace --trace trace_example.py --- modulename: trace_example, funcname: <module> trace_example.py(1): class Student: --- modulename: trace_example, funcname: Student trace_example.py(1): class Student: trace_example.py(2): def __init__(self, std): trace_example.py(5): def go(self): trace_example.py(9): if __name__ == '__main__': trace_example.py(10): Student(5).go() --- modulename: trace_example, funcname: __init__ trace_example.py(3): self.count = std --- modulename: trace_example, funcname: go trace_example.py(6): for i in range(self.count): trace_example.py(7): print(i) 0 trace_example.py(6): for i in range(self.count): trace_example.py(7): print(i) 1 trace_example.py(6): for i in range(self.count): trace_example.py(7): print(i) 2 trace_example.py(6): for i in range(self.count): trace_example.py(7): print(i) 3 trace_example.py(6): for i in range(self.count): trace_example.py(7): print(i) 4 trace_example.py(6): for i in range(self.count): trace_example.py(8): return --- modulename: trace, funcname: _unsettrace trace.py(77): sys.settrace(None)
Q群内免费获取887934385 工具
分析Python程序意味着测量程序的执行时间。它衡量每一个功能所花费的时间。 Python的cProfile模块用于分析Python程序。性能
cProfile模块
如前所述,分析意味着测量程序的执行时间。咱们将使用cProfile Python模块来分析程序。学习
如今,咱们将编写一个cprof_example.py脚本并在其中编写如下代码:测试
mul_value = 0 def mul_numbers( num1, num2 ): mul_value = num1 * num2; print ("Local Value: ", mul_value) return mul_value mul_numbers( 58, 77 ) print ("Global Value: ", mul_value)
执行:ui
$ python3 -m cProfile cprof_example.py Local Value: 4466 Global Value: 0 6 function calls in 0.000 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 cprof_example.py:1(<module>) 1 0.000 0.000 0.000 0.000 cprof_example.py:3(mul_numbers) 1 0.000 0.000 0.000 0.000 {built-in method builtins.exec} 2 0.000 0.000 0.000 0.000 {built-in method builtins.print} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
使用timeit,咱们能够决定咱们想要测量哪些代码的性能。所以,咱们能够轻松定义设置代码以及咱们要单独执行测试的代码段。主代码运行100万次,这是默认时间,而设置代码只运行一次。spa
import timeit prg_setup = "from math import sqrt" prg_code = ''' def timeit_example(): list1 = [] for x in range(50): list1.append(sqrt(x)) ''' # timeit statement print(timeit.timeit(setup = prg_setup, stmt = prg_code, number = 10000))
执行:
$ python timeit_example.py
0.00180888175964
有多种方法能够使Python程序运行得更快,以下所示:
在本章中,咱们了解了调试和分析程序的重要性。咱们了解了可用于调试的不一样技术。咱们了解了pdb Python调试器以及如何处理异常。咱们在分析和计时脚本时学习了如何使用Python的cProfile和timeit模块。咱们还学习了如何使脚本运行得更快。