| 1 |
""" |
| 2 |
JinjaX Benchmark |
| 3 |
Copyright (c) Juan-Pablo Scaletti <[email protected]> |
| 4 |
""" |
| 5 |
import timeit |
| 6 |
from pathlib import Path |
| 7 |
|
| 8 |
from fastapi.templating import Jinja2Templates |
| 9 |
from jinja2 import Environment, FileSystemLoader |
| 10 |
|
| 11 |
from jinjax import Catalog |
| 12 |
|
| 13 |
|
| 14 |
here = Path(__file__).parent |
| 15 |
number = 10_000 |
| 16 |
|
| 17 |
catalog = Catalog() |
| 18 |
catalog.add_folder(here) |
| 19 |
|
| 20 |
env = Environment(loader=FileSystemLoader(here)) |
| 21 |
|
| 22 |
templates = Jinja2Templates(directory=here) |
| 23 |
|
| 24 |
|
| 25 |
def render_jinjax_simple(): |
| 26 |
"""simple case""" |
| 27 |
catalog.render("Simple", message="Hey there") |
| 28 |
|
| 29 |
|
| 30 |
def render_jinjax_real(): |
| 31 |
"""realistic case""" |
| 32 |
catalog.render("Real", message="Hey there") |
| 33 |
|
| 34 |
|
| 35 |
def render_jinja(): |
| 36 |
env.get_template("hello.html").render(message="Hey there") |
| 37 |
|
| 38 |
|
| 39 |
def render_fastapi(): |
| 40 |
templates.TemplateResponse("hello.html", {"request": None, "message": "Hey there"}) |
| 41 |
|
| 42 |
|
| 43 |
def benchmark_no_cache(func): |
| 44 |
print(f"NO CACHE: {number:_} renders of {func.__doc__}...\n") |
| 45 |
catalog.use_cache = False |
| 46 |
benchmark(func) |
| 47 |
|
| 48 |
|
| 49 |
def benchmark_auto_reload(func): |
| 50 |
print(f"CACHE, AUTO-RELOAD: {number:_} renders of {func.__doc__}...\n") |
| 51 |
catalog.use_cache = True |
| 52 |
catalog.auto_reload = True |
| 53 |
benchmark(func) |
| 54 |
|
| 55 |
|
| 56 |
def benchmark_no_auto_reload(func): |
| 57 |
print(f"CACHE, NO AUTO-RELOAD: {number:_} renders of {func.__doc__}...\n") |
| 58 |
catalog.use_cache = True |
| 59 |
catalog.auto_reload = False |
| 60 |
benchmark(func) |
| 61 |
|
| 62 |
|
| 63 |
def benchmark(func): |
| 64 |
time_jinjax = timeit.timeit(func, number=number) |
| 65 |
print_line("JinjaX", time_jinjax) |
| 66 |
print(f"{time_jinjax / time_jinja:.1f} times Jinja") |
| 67 |
print(f"{time_jinjax / time_fastapi:.1f} times FastApi") |
| 68 |
|
| 69 |
|
| 70 |
def print_line(name, time): |
| 71 |
print(f"{name}: {(time / number):.12f}s per render ({(1_000_000 * time / number):.0f}µs), {time:.1f}s total") |
| 72 |
|
| 73 |
|
| 74 |
def print_separator(): |
| 75 |
print() |
| 76 |
print("-" * 60) |
| 77 |
|
| 78 |
|
| 79 |
if __name__ == "__main__": |
| 80 |
print("Benchmarking...\n") |
| 81 |
time_jinja = timeit.timeit(render_jinja, number=number) |
| 82 |
time_fastapi = timeit.timeit(render_fastapi, number=number) |
| 83 |
|
| 84 |
print_line("Jinja", time_jinja) |
| 85 |
print_line("FastApi", time_fastapi) |
| 86 |
print_separator() |
| 87 |
benchmark_auto_reload(render_jinjax_real) |
| 88 |
print() |
| 89 |
benchmark_no_auto_reload(render_jinjax_real) |
| 90 |
print() |