1. 程式人生 > 其它 >Python3逐行分析程式碼執行時間

Python3逐行分析程式碼執行時間

Python3 有一個很好用的第三方庫叫 line_profiler 可以分析每行程式碼的執行時間及佔比

安裝

pip install line_profiler

使用

# @Coding: utf-8
# @Time: 2021/8/5 3:54 下午
from line_profiler import LineProfiler


def test(num1, num2):
    num3 = num1 ** num2
    print(num3)


if __name__ == '__main__':
    # 正常呼叫
    # test(2, 3)
    # 分析時間
    lp = LineProfiler()
    lp_wrapper 
= lp(test) lp_wrapper(2, 3) lp.print_stats()

結果

8
Timer unit: 1e-06 s

Total time: 3.9e-05 s
File: /Users/wangwenjie/code/test/1111111.py
Function: test at line 8

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     8
def test(num1, num2): 9 1 8.0 8.0 20.5 num3 = num1 ** num2 10 1 31.0 31.0 79.5 print(num3) Process finished with exit code 0