Skip to content

Commit

Permalink
also benchmark production-grade ways of loading templates in Django a…
Browse files Browse the repository at this point in the history
…nd Jinja2
  • Loading branch information
ambv committed Apr 12, 2013
1 parent 6aae051 commit 40c877d
Showing 1 changed file with 32 additions and 12 deletions.
44 changes: 32 additions & 12 deletions microtemplates/benchmarks.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import os
import timeit
from jinja2 import Template as JinjaTemplate
from jinja2 import Environment, FileSystemLoader, Template as JinjaTemplate
from django.conf import settings
from django.template import Context, Template as DjangoTemplate
from .base import Template as MicroTemplate
from django.template.loaders.filesystem import Loader as DjangoDefaultLoader
from django.template.loaders.cached import Loader as DjangoCachedLoader
from base import Template as MicroTemplate

settings.configure()

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
context = {
Expand All @@ -17,6 +18,7 @@
]
}

settings.configure(TEMPLATE_DIRS=[template_dir])

def read_html(engine):
html_file_path = os.path.join(template_dir, "%s.html" % engine)
Expand All @@ -25,27 +27,45 @@ def read_html(engine):
return html


microtemplates_html = read_html('microtemplates')
django_html = read_html('django')
django_default_loader = DjangoDefaultLoader()
django_cached_loader = DjangoCachedLoader(['django.template.loaders.filesystem.Loader'])
jinja2_html = read_html('jinja2')
jinja2_env = Environment(loader=FileSystemLoader(template_dir))


def benchmark_microtemplates():
html = read_html('microtemplates')
MicroTemplate(html).render(**context)
MicroTemplate(microtemplates_html).render(**context)


def benchmark_django():
html = read_html('django')
DjangoTemplate(html).render(Context(context))
DjangoTemplate(django_html).render(Context(context))


def benchmark_django_default_loader():
template, _ = django_default_loader.load_template('django.html')
template.render(Context(context))


def benchmark_django_cached_loader():
template, _ = django_cached_loader.load_template('django.html')
template.render(Context(context))


def benchmark_jinja2():
html = read_html('jinja2')
JinjaTemplate(html).render(**context)
JinjaTemplate(jinja2_html).render(**context)


def benchmark_jinja2_env():
jinja2_env.get_template('jinja2.html').render(**context)


if __name__ == '__main__':
number = 1000
engines = ('microtemplates', 'django', 'jinja2')
number = 10000
engines = ('microtemplates', 'django', 'django_default_loader', 'django_cached_loader', 'jinja2', 'jinja2_env')
setup = "from __main__ import %s" % ', '.join(map(lambda t: 'benchmark_' + t, engines))
for engine in engines:
t = timeit.Timer("benchmark_%s()" % engine, setup=setup)
time = t.timeit(number=number) / number
print "%s => run %s times, took %.2f ms" % (engine, number, 1000 * time)

0 comments on commit 40c877d

Please sign in to comment.