py-spy is a sampling profiler for Python programs. It lets you visualize what your Python program is spending time on without restarting the program or modifying the code in any way. py-spy is extremely low overhead: it is written in Rust for speed and doesn't run in the same process as the profiled Python program. This means py-spy is safe to use against production Python code.
py-spy works on Linux, OSX, Windows and FreeBSD, and supports profiling all recent versions of the CPython interpreter (versions 2.3-2.7 and 3.3-3.9).
This article shows a demonstration of how to use py-spy to run sampling profiler for your Python application running in Linux App Service.
In your Python application project, find your requirements.txt file. Add "py-spy" in the file.
This is the only change we need to make. No other code changes are required.
When deploying the code, Azure orxy build will help us install the py-spy package.
Py-spy allow us attach to a running Python process, and monitor its performance.
The tool is similar to the Unix top command, it shows a live view of what functions are taking the most time in your python program, . Running py-spy with:
Here is my sample Python code. When I access http://<webapp-name>.azurewebsites.net/test2, I can see a lot cpu time consumed by my runjob2() function.
import time
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
runjob()
return "Hello Azure, from Flask!"
@app.route("/test1")
def test1():
return "Hello Test1!"
@app.route("/test2")
def test2():
runjob2()
return "Hello Test2!"
def runjob():
counter = []
for i in range(0,5):
test()
counter.append(i)
print (counter)
def runjob2():
for i in range(0,10):
i = i+1
time.sleep(1)
def test():
print(">>>>>start test")
time.sleep(1)
print("<<<<<<<done")
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.