added a semi realworld benchmark (jinja2 and mako)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent e9411b4 · Browse files · 10 files·+228 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+228 added−8 removed
- other:+228 added−8 removed
Provenance
- Commit
dc02b64- Tree
5fa0aa3- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e9411b4
10 files changed+228 added−8 removed
added:examples/rwbench/jinja/helpers.html+12 added
123456789101112{% macro input_field(name, value='', type='text') -%} <input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">{%- endmacro %}
{% macro textarea(name, value='', rows=10, cols=40) -%} <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{ value|e }}</textarea>{%- endmacro %}
{% macro form(action='', method='post') -%} <form action="{{ action|e }}" method="{{ method }}">{{ caller() }}</form>{%- endmacro %}added:examples/rwbench/jinja/index.html+26 added
1234567891011121314151617181920212223242526{% extends "layout.html" %}{% from "helpers.html" import input_field, textarea, form %}{% block page_title %}Index Page{% endblock %}{% block body %} {%- for article in articles %} <div class="article"> <h2><a href="{{ article.href|e }}">{{ article.title|e }}</a></h2> <p class="meta">written by <a href="{{ article.user.href|e }}">{{ article.user.username|e }}</a> on {{ article.pub_date|dateformat }}</p> <div class="text">{{ article.body }}</div> </div> {%- endfor %} {%- call form() %} <dl> <dt>Name</dt> <dd>{{ input_field('name') }}</dd> <dt>E-Mail</dt> <dd>{{ input_field('email') }}</dd> <dt>URL</dt> <dd>{{ input_field('url') }}</dd> <dt>Comment</dd> <dd>{{ textarea('comment') }}</dd> </dl> {{ input_field(type='submit', value='Submit') }} {%- endcall %}{% endblock %}added:examples/rwbench/jinja/layout.html+29 added
1234567891011121314151617181920212223242526272829<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head> <title>{% block page_title %}{% endblock %} | RealWorld Benchmark</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body> <div class="contents"> <div class="header"> <h1>RealWorld Benchmark</h1> <blockquote><p> A less stupid benchmark for Mako and Jinja2 to get an impression how code changes affect runtime performance. </p></blockquote> </div> <ul class="navigation"> {%- for href, caption in page_navigation %} <li><a href="{{ href|e }}">{{ caption }}</a></li> {%- endfor %} </ul> <div class="body"> {% block body %}{% endblock %} </div> <div class="footer"> © Copyright 2008 by I don't know who. </div> </div></body></html>added:examples/rwbench/mako/helpers.html+11 added
1234567891011<%def name="input_field(name='', value='', type='text')"> <input type="${type}" value="${value|h}" name="${name}"></%def>
<%def name="textarea(name, value='', rows=10, cols=40)"> <textarea name="${name}" rows="${rows}" cols="${cols}">${value|h}</textarea></%def>
<%def name="form(action='', method='post')"> <form action="${action|h}" method="${method}">${caller.body()}</form></%def>added:examples/rwbench/mako/index.html+27 added
123456789101112131415161718192021222324252627<%! from rwbench import dateformat%><%inherit file="layout.html" /><%namespace file="helpers.html" import="input_field, textarea, form" /><%def name="page_title()">Index Page</%def>% for article in articles:<div class="article"> <h2><a href="${article.href|h}">${article.title|h}</a></h2> <p class="meta">written by <a href="${article.user.href|h }">${article.user.username|h}</a> on ${dateformat(article.pub_date)}</p> <div class="text">${article.body}</div></div>% endfor<%call expr="form()"> <dl> <dt>Name</dt> <dd>${input_field('name')}</dd> <dt>E-Mail</dt> <dd>${input_field('email')}</dd> <dt>URL</dt> <dd>${input_field('url')}</dd> <dt>Comment</dd> <dd>${textarea('comment')}</dd> </dl> ${input_field(type='submit', value='Submit')}</%call>added:examples/rwbench/mako/layout.html+30 added
123456789101112131415161718192021222324252627282930<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head> <title>${self.page_title()} | RealWorld Benchmark</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body> <div class="contents"> <div class="header"> <h1>RealWorld Benchmark</h1> <blockquote><p> A less stupid benchmark for Mako and Jinja2 to get an impression how code changes affect runtime performance. </p></blockquote> </div> <ul class="navigation"> % for href, caption in page_navigation: <li><a href="${href|h}">${caption}</a></li> % endfor </ul> <div class="body"> ${self.body()} </div> <div class="footer"> © Copyright 2008 by I don't know who. </div> </div></body></html><%def name="page_title()"></%def>added:examples/rwbench/rwbench.py+83 added
1+# -*- coding: utf-8 -*-2+"""3+ RealWorldish Benchmark4+ ~~~~~~~~~~~~~~~~~~~~~~5+6+ A more real-world benchmark of Jinja2.7+8+ :copyright: Copyright 2008 by Armin Ronacher.9+ :license: BSD.10+"""11+import sys12+from os.path import join, dirname, abspath13+from random import choice, randrange14+from datetime import datetime15+from timeit import Timer16+from jinja2 import Environment, FileSystemLoader17+from jinja2.utils import generate_lorem_ipsum18+from mako.lookup import TemplateLookup19+20+21+ROOT = abspath(dirname(__file__))22+23+24+def dateformat(x):25+ return x.strftime('%Y-%m-%d')26+27+28+jinja_env = Environment(loader=FileSystemLoader(join(ROOT, 'jinja')))29+jinja_env.filters['dateformat'] = dateformat30+31+mako_lookup = TemplateLookup(directories=[join(ROOT, 'mako')])32+33+34+class Article(object):35+36+ def __init__(self, id):37+ self.id = id38+ self.href = '/article/%d' % self.id39+ self.title = generate_lorem_ipsum(1, False, 5, 10)40+ self.user = choice(users)41+ self.body = generate_lorem_ipsum()42+ self.pub_date = datetime.utcfromtimestamp(randrange(1000000000,43+ 2000000000))44+45+46+class User(object):47+48+ def __init__(self, username):49+ self.href = '/user/%s' % username50+ self.username = username51+52+53+users = map(User, [u'John Doe', u'Jane Doe', u'Peter Somewhat'])54+articles = map(Article, range(20))55+navigation = [56+ ('index', 'Index'),57+ ('about', 'About'),58+ ('foo?bar=1', 'Foo with Bar'),59+ ('foo?bar=2&s=x', 'Foo with X')60+]61+62+context = dict(users=users, articles=articles, page_navigation=navigation)63+64+65+jinja_template = jinja_env.get_template('index.html')66+mako_template = mako_lookup.get_template('index.html')67+68+69+def test_jinja():70+ jinja_template.render(context)71+72+def test_mako():73+ mako_template.render_unicode(**context)74+75+76+if __name__ == '__main__':77+ sys.stdout.write('Realworldish Benchmark:\n')78+ for test in 'jinja', 'mako':79+ t = Timer(setup='from __main__ import test_%s as bench' % test,80+ stmt='bench()')81+ sys.stdout.write(' >> %-20s<running>' % test)82+ sys.stdout.flush()83+ sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50))modified:jinja2/compiler.py+5 added-3 removed
271 unmodified lines272 self.generic_visit(node)273 if isinstance(node.arg, nodes.Const) and \274 isinstance(node.arg.value, basestring) and \275 ((isinstance(node.node, nodes.Name) and276+ # this code ignores parameter declared names as the may only277+ # occour at the very beginning of a scope and we pull the278+ # attributes afterwards.279 node.node.name not in (self.identifiers.declared_locally)) or280 node.node in self.identifiers.static_subscribes):281 if node in self.identifiers.static_subscribes:282 self.identifiers.static_subscribes[node] += 1283 else:284 self.identifiers.static_subscribes[node] = 1285 286 def visit_Macro(self, node):284- self.generic_visit(node)287 self.identifiers.declared_locally.add(node.name)288 289 def visit_Import(self, node):290 self.generic_visit(node)375 unmodified lines666 else:667 self.writeline('import %s as %s' % (imp, alias))668 669 # add the load name668- self.writeline('name = %r' % self.filename)670+ self.writeline('name = %r' % self.name)671 672 # generate the root render function.673 self.writeline('def root(context, environment=environment):', extra=1)674 175 unmodified lines850 '%r, missing)' % (alias, name))851 self.writeline('if l_%s is missing:' % alias)852 self.indent()853 self.writeline('l_%s = environment.undefined(%r %% '852- 'included_template.name, '854+ 'included_template.__name__, '855 'name=%r)' %856 (alias, 'the template %r does not export '857 'the requested name ' + repr(name), name))858 self.outdent()569 unmodified linesmodified:jinja2/environment.py+1 added-1 removed
607 unmodified lines608 def __repr__(self):609 if self.__name__ is None:610 name = 'memory:%x' % id(self)611 else:612- name = repr(self.name)612+ name = repr(self.__name__)613 return '<%s %s>' % (self.__class__.__name__, name)614 615 616 class TemplateStream(object):58 unmodified linesmodified:jinja2/runtime.py+4 added-4 removed
19 unmodified lines20 'TemplateRuntimeError', 'missing', 'concat', 'escape',21 'markup_join', 'unicode_join']22 23 24-def markup_join(*args):24+def markup_join(seq):25 """Concatenation that escapes if necessary and converts to unicode."""26 buf = []27- iterator = imap(soft_unicode, args)27+ iterator = imap(soft_unicode, seq)28 for arg in iterator:29 buf.append(arg)30 if hasattr(arg, '__html__'):31 return Markup(u'').join(chain(buf, iterator))32 return concat(buf)33 34 35-def unicode_join(*args):35+def unicode_join(seq):36 """Simple args to unicode conversion and concatenation."""37- return concat(imap(unicode, args))37+ return concat(imap(unicode, seq))38 39 40 class Context(object):41 """The template context holds the variables of a template. It stores the380 unmodified lines