用 Py-Spy 分析 Python 程式效率

這之後應該會變成 Python community 的神器之一...

剛剛看到分析 Python 程式效率的工具,只要有 pid 或是直接包著跑就可以分析:「Py-Spy: A sampling profiler for Python programs.」,執行起來長這樣:

而且還可以直接產生火焰圖讓開發者直接確認,超友善:

在 FAQ 的地方也有提到作者開發這套軟體的原因。有些在開發環境根本看不出問題的,可以很快的透過這個工具在 production 上看:

This project aims to let you profile and debug any running Python program, even if the program is serving production traffic.

另外一個重點在於其他常見的 profiling 工具通常都要改程式引用進來使用,這通常會使得程式效率慢下來,而 Pyflame 支援的平台比較少:

While there are many other python profiling projects, almost all of them require modifying the profiled program in some way. Usually, the profiling code runs inside of the target python process, which will slow down and change how the program operates. This means it's not generally safe to use these profilers for debugging issues in production services since they will usually have a noticeable impact on performance. The only other Python profiler that runs totally in a separate process is pyflame, which profiles remote python processes by using the ptrace system call. While pyflame is a great project, it doesn't support Python 3.7 yet and doesn't work on OSX or Windows.

Leave a Reply

Your email address will not be published. Required fields are marked *