DEV Community

CodingShower
CodingShower

Posted on

Profiling Flask Apps

When you're working on Flask apps, at some point one of your routes could get slow in terms of performance (returning response to the client).

The best way to approach such problems (slow programs) is to use a profiler to analyse which parts of your code is slowing down the application.

In Flask we can use the Werkzeug Profiler Middleware to implement profiling in our Flask apps. It is super simple!

from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware

app = Flask(...)
app.wsgi_app = ProfilerMiddleware(app.wsgi_app)
Enter fullscreen mode Exit fullscreen mode

That's it! Now when you make a request to one of your endpoints, in your console log, you'll notice stats getting dumped.

----------------------------------------
PATH: '/search'
         7508936 function calls (7492431 primitive calls) in 3.824 seconds

   Ordered by: internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.701    0.701    2.152    2.152 ...
   101132    0.485    0.000    0.485    0.000 ...
   166457    0.351    0.000    1.258    0.000 ...
  1440656    0.226    0.000    0.347    0.000 ...
5048/4702    0.165    0.000    0.327    0.000 ...
       ...

----------------------------------------
Enter fullscreen mode Exit fullscreen mode
  • If you'd like to learn more about configuring the profiler, head over to this article.
  • If you'd like to learn more about using a statistical profiler, head over to this article.

Top comments (0)