| 1 |
import cProfile |
| 2 |
import profile |
| 3 |
from timeit import Timer |
| 4 |
|
| 5 |
import django.conf |
| 6 |
import django.template.loader |
| 7 |
|
| 8 |
import pyinstrument |
| 9 |
|
| 10 |
django.conf.settings.configure( |
| 11 |
INSTALLED_APPS=(), |
| 12 |
TEMPLATES=[ |
| 13 |
{ |
| 14 |
"BACKEND": "django.template.backends.django.DjangoTemplates", |
| 15 |
"DIRS": [ |
| 16 |
"./examples/demo_scripts/django_example/django_example/templates", |
| 17 |
], |
| 18 |
} |
| 19 |
], |
| 20 |
) |
| 21 |
django.setup() |
| 22 |
|
| 23 |
|
| 24 |
def test_func_template(): |
| 25 |
django.template.loader.render_to_string("template.html") |
| 26 |
|
| 27 |
|
| 28 |
t = Timer(stmt=test_func_template) |
| 29 |
test_func = lambda: t.repeat(number=4000) |
| 30 |
|
| 31 |
|
| 32 |
base_timings = test_func() |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
cp = cProfile.Profile() |
| 40 |
cProfile_timings = cp.runcall(test_func) |
| 41 |
|
| 42 |
|
| 43 |
profiler = pyinstrument.Profiler() |
| 44 |
profiler.start() |
| 45 |
pyinstrument_timings = test_func() |
| 46 |
profiler.stop() |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
profiler.write_html("out.html") |
| 55 |
|
| 56 |
print(profiler.output_text(unicode=True, color=True)) |
| 57 |
|
| 58 |
graph_data = ( |
| 59 |
("Base timings", min(base_timings)), |
| 60 |
|
| 61 |
("cProfile", min(cProfile_timings)), |
| 62 |
("pyinstrument", min(pyinstrument_timings)), |
| 63 |
|
| 64 |
) |
| 65 |
|
| 66 |
GRAPH_WIDTH = 60 |
| 67 |
print("Profiler overhead") |
| 68 |
print("–" * (GRAPH_WIDTH + 17)) |
| 69 |
max_time = max([t[1] for t in graph_data]) |
| 70 |
for name, time in graph_data: |
| 71 |
chars = int((time / max_time) * GRAPH_WIDTH) |
| 72 |
spaces = GRAPH_WIDTH - chars |
| 73 |
print(f'{name:15} {"█" * chars}{" " * spaces} {time:.3f}s') |
| 74 |
print() |