Skip to content

Instantly share code, notes, and snippets.

@roymanigley
Created March 26, 2024 06:35
Show Gist options
  • Save roymanigley/1877a5d10d718bbb82c84099abb6fbbc to your computer and use it in GitHub Desktop.
Save roymanigley/1877a5d10d718bbb82c84099abb6fbbc to your computer and use it in GitHub Desktop.
Django Profiling

Django Profiling

Dependencies

requirements.txt

django-cprofile-middleware==1.0.5
django-silk==5.1.0
snakeviz==2.2.0
pyprof2calltree==1.4.5

Command line tool

sudo apt install kcachegrind

Setup & Usage

cProfile

settings.py

MIDDLEWARE = [
  'django_cprofile_middleware.middleware.ProfilerMiddleware',
  ...
]

DJANGO_CPROFILE_MIDDLEWARE_REQUIRE_STAFF = False

Usage (snakeviz)

  1. download statistics:

    GET {{ _.url }}?prof&count=9999999&sort=cumtime&download

  2. analyze the profiling results:

    snakeviz /tmp/cprofile.bin

Usage (kcachegrind)

  1. download statistics:

    GET {{ _.url }}?prof&count=9999999&sort=cumtime&download

  2. analyze the profiling results:

    pyprof2calltree -i /tmp/cprofile.bin -o /tmp/cprofile.calltree`
    kcachegrind /tmp/cprofile.calltree
    

django-silk

1. settings.py

INSTALLED_APPS = [
    'silk',
    ...
]

MIDDLEWARE = [    
  'silk.middleware.SilkyMiddleware',
  ...
]

SILKY_PYTHON_PROFILER = True

2. migrations

python manage.py makemigrations
python manage.py migrate

3. urls.py

from django.urls import path, include

urlpatterns += [
  path("silk/", include("silk.urls", namespace="silk"))
]

Usage

http://localhost:8000/silk/

add profiling:
from silk.profiling.profiler import silk_profile

with snake_profile('some-descriptive-name'):
  my_method()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment