added spitfire to bench and did some more refactoring
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 5304229 · Browse files · 6 files·+114 added−91 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+114 added−91 removed
- other:+114 added−91 removed
Provenance
- Commit
32a910f- Tree
c128d72- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
5304229
6 files changed+114 added−91 removed
modified:examples/bench.py+56 added-8 removed
1-"""1+"""\2 This benchmark compares some python templating engines with Jinja 2 so3 that we get a picture of how fast Jinja 2 is for a semi real world4- template. If a template engine is not installed the test is skipped.4+ template. If a template engine is not installed the test is skipped.\5 """6 import sys7+import cgi8 from timeit import Timer9 from jinja2 import Environment as JinjaEnvironment10 11 context = {235 unmodified lines247 def test_tenjin():248 from tenjin.helpers import escape, to_str249 tenjin_template.render(context, locals())250 251+try:252+ from spitfire.compiler import util as SpitfireTemplate253+ from spitfire.compiler.analyzer import o2_options as spitfire_optimizer254+except ImportError:255+ test_spitfire = None256+else:257+ spitfire_template = SpitfireTemplate.load_template("""\258+<!doctype html>259+<html>260+ <head>261+ <title>$cgi.escape($page_title)</title>262+ </head>263+ <body>264+ <div class="header">265+ <h1>$cgi.escape($page_title)</h1>266+ </div>267+ <ul class="navigation">268+ #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]269+ <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li>270+ #end for271+ </ul>272+ <div class="table">273+ <table>274+ #for $row in $table275+ <tr>276+ #for $cell in $row277+ <td>$cell</td>278+ #end for279+ </tr>280+ #end for281+ </table>282+ </div>283+ </body>284+</html>\285+""", 'spitfire_tmpl', spitfire_optimizer, {'enable_filters': False})286+ spitfire_context = dict(context, **{'cgi': cgi})287+288+ def test_spitfire():289+ spitfire_template(search_list=[spitfire_context]).main()290+291 sys.stdout.write('\r' + '\n'.join((292 '=' * 80,293 'Template Engine BigTable Benchmark'.center(80),253- '-' * 80,294+ '=' * 80,295 __doc__,296 '-' * 80297 )) + '\n')257-for test in 'jinja', 'tenjin', 'mako', 'django', 'genshi', 'cheetah':298+for test in 'jinja', 'tenjin', 'mako', 'spitfire', 'django', 'genshi', 'cheetah':299 if locals()['test_' + test] is None:259- sys.stdout.write(' %-20s*not installed*\n' % test)300+ sys.stdout.write(' %-20s*not installed*\n' % test)301 continue302 t = Timer(setup='from __main__ import test_%s as bench' % test,303 stmt='bench()')263- sys.stdout.write('> %-20s<running>' % test)304+ sys.stdout.write(' >> %-20s<running>' % test)305 sys.stdout.flush()265- sys.stdout.write('\r %-20s%.4f ms\n' % (test, t.timeit(number=20) / 20))266-sys.stdout.write('=' * 80 + '\n')306+ sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=20) / 20))307+sys.stdout.write('-' * 80 + '\n')308+sys.stdout.write('''\309+ WARNING: The results of this benchmark are useless to compare the310+ performance of template engines and should not be taken seriously in any311+ way. It's testing the performance of simple loops and has no real-world312+ usefulnes. It only used to check if changes on the Jinja code affect313+ performance in a good or bad way and how it roughly compares to others.314+''' + '=' * 80 + '\n')modified:jinja2/compiler.py+21 added-15 removed
6 unmodified lines7 8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10 """11+from time import time12 from copy import copy13 from random import randrange14 from keyword import iskeyword15 from cStringIO import StringIO16 from itertools import chain17 from jinja2 import nodes18 from jinja2.visitor import NodeVisitor, NodeTransformer19 from jinja2.exceptions import TemplateAssertionError19-from jinja2.runtime import StaticLoopContext, concat20+from jinja2.runtime import concat21 from jinja2.utils import Markup22 23 24 operators = {28 unmodified lines53 """Does the node have a safe representation?"""54 if value is None or value is NotImplemented or value is Ellipsis:55 return True56 if isinstance(value, (bool, int, long, float, complex, basestring,56- xrange, StaticLoopContext, Markup)):57+ xrange, Markup)):58 return True59 if isinstance(value, (tuple, list, set, frozenset)):60 for item in value:61 if not has_safe_repr(item):483 unmodified lines545 self.name)546 self.blocks[block.name] = block547 548 # generate the root render function.548- self.writeline('def root(context, environment=environment'549- '):', extra=1)549+ self.writeline('def root(context, environment=environment):', extra=1)550 if have_extends:551 self.indent()552 self.writeline('parent_template = None')553 self.outdent()205 unmodified lines759 # tests in not extended loops become a continue760 if not extended_loop and node.test is not None:761 self.indent()762 self.writeline('if ')763- self.visit(node.test)763+ self.visit(node.test, loop_frame)764 self.write(':')765 self.indent()766 self.writeline('continue')767 self.outdent(2)33 unmodified lines801 self.writeline("return Markup(concat(%s))" % buf)802 self.outdent()803 self.newline()804 if frame.toplevel:805- self.write('context[%r] = ' % node.name)805+ self.write('context.exported_vars.add(%r)' % node.name)806+ self.writeline('context.vars[%r] = ' % node.name)807 arg_tuple = ', '.join(repr(x.name) for x in node.args)808 if len(node.args) == 1:809 arg_tuple += ','810 self.write('l_%s = Macro(environment, macro, %r, (%s), (' %98 unmodified lines909 body[-1].append(const)910 else:911 body.append([const])912 912- # if we have less than 3 nodes we just yield them913- if len(body) < 3:913+ # if we have less than 3 nodes or less than 6 and a buffer we914+ # yield or extend915+ if len(body) < 3 or (frame.buffer is not None and len(body) < 6):916+ if frame.buffer is not None:917+ self.writeline('%s.extend((' % frame.buffer)918 for item in body:919 if isinstance(item, list):920 val = repr(concat(item))921 if frame.buffer is None:922 self.writeline('yield ' + val)923 else:920- self.writeline('%s.append(%s)' % (frame.buffer, val))924+ self.write(val + ', ')925 else:922- self.newline(item)926 if frame.buffer is None:924- self.write('yield ')925- else:926- self.write('%s.append(' % frame.buffer)927+ self.writeline('yield ')928 self.write(finalizer + '(')929 self.visit(item, frame)929- self.write(')' * (1 + (frame.buffer is not None)))930+ self.write(')')931+ if frame.buffer is not None:932+ self.write(', ')933+ if frame.buffer is not None:934+ self.write('))')935 936 # otherwise we create a format string as this is faster in that case937 else:938 format = []44 unmodified lines983 984 # make sure toplevel assignments are added to the context.985 if frame.toplevel:986 for name in assignment_frame.assigned_names:982- self.writeline('context[%r] = l_%s' % (name, name))987+ self.writeline('context.vars[%r] = l_%s' % (name, name))988+ self.writeline('context.exported_vars.add(%r)' % name)989 990 def visit_Name(self, node, frame):991 if node.ctx == 'store':992 if frame.toplevel:170 unmodified linesmodified:jinja2/debug.py+25 added-3 removed
7 unmodified lines8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10 """11 import sys12+from types import CodeType13 14 15 def translate_exception(exc_info):16 """If passed an exc_info it will automatically rewrite the exceptions44 unmodified lines61 62 # and fake the exception63 code = compile('\n' * (lineno - 1) + 'raise __jinja_exception__[0], ' +64 '__jinja_exception__[1]', filename, 'exec')65+66+ # if it's possible, change the name of the code. This won't work67+ # on some python environments such as google appengine68 try:69+ function = tb.tb_frame.f_code.co_name70+ if function == 'root':71+ location = 'top-level template code'72+ elif function.startswith('block_'):73+ location = 'block "%s"' % function[6:]74+ else:75+ location = 'template'76+ code = CodeType(0, code.co_nlocals, code.co_stacksize,77+ code.co_flags, code.co_code, code.co_consts,78+ code.co_names, code.co_varnames, filename,79+ location, code.co_firstlineno,80+ code.co_lnotab, (), ())81+ except:82+ pass83+84+ # execute the code and catch the new traceback85+ try:86 exec code in globals, locals87 except:88 exc_info = sys.exc_info()89+ new_tb = exc_info[2].tb_next90 91 # now we can patch the exc info accordingly92 if tb_set_next is not None:93 if tb_back is not None:72- tb_set_next(tb_back, exc_info[2])94+ tb_set_next(tb_back, new_tb)95 if tb is not None:74- tb_set_next(exc_info[2].tb_next, tb.tb_next)96+ tb_set_next(new_tb, tb.tb_next)97 98 # return without this frame77- return exc_info[:2] + (exc_info[2].tb_next,)99+ return exc_info[:2] + (new_tb,)100 101 102 def _init_ugly_crap():103 """This function implements a few ugly things so that we can patch the68 unmodified linesmodified:jinja2/environment.py+1 added-2 removed
229 unmodified lines230 if self.loader is None:231 raise TypeError('no loader for this environment specified')232 if parent is not None:233 name = self.join_path(name, parent)234- globals = self.make_globals(globals)235- return self.loader.load(self, name, globals)234+ return self.loader.load(self, name, self.make_globals(globals))235 236 def from_string(self, source, globals=None, template_class=None):237 """Load a template from a string."""238 globals = self.make_globals(globals)232 unmodified linesmodified:jinja2/parser.py+1 added-2 removed
683 unmodified lines684 self.stream.next()685 if end_tokens is not None and \686 self.stream.current.test_many(end_tokens):687 return body688- while self.stream.current.type is not 'block_end':689- body.append(self.parse_statement())688+ body.append(self.parse_statement())689 self.stream.expect('block_end')690 else:691 raise AssertionError('internal parsing error')692 8 unmodified linesmodified:jinja2/runtime.py+10 added-61 removed
12 unmodified lines13 from jinja2.exceptions import UndefinedError14 15 16 # these variables are exported to the template runtime17-__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',18- 'Macro', 'Markup', 'missing', 'concat']17+__all__ = ['LoopContext', 'TemplateContext', 'Macro', 'Markup', 'missing',18+ 'concat']19 20 21 # special singleton representing missing values for the runtime22-missing = object()22+missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()23 24 25 # concatenate a list of strings and convert them to unicode.26 concat = u''.join45 unmodified lines72 if key in self.parent:73 return self.parent[key]74 return default75 76- def setdefault(self, key, default=None):77- """For dict compatibility"""78- self.exported_vars.add(key)79- return self.vars.setdefault(key, default)80-81- def update(self, *args, **kwargs):82- """Update vars from a mapping but don't export them."""83- d = dict(*args, **kwargs)84- self.vars.update(d)85- self.exported_vars.update(d)86-76 def get_exported(self):77 """Get a new dict with the exported variables."""78 return dict((k, self.vars[k]) for k in self.exported_vars79 if not k.startswith('__'))5 unmodified lines85 def get_all(self):86 """Return a copy of the complete context as dict."""87 return dict(self.parent, **self.vars)88 100- def __setitem__(self, key, value):101- self.vars[key] = value102- self.exported_vars.add(key)103-89 def __contains__(self, name):90 return name in self.vars or name in self.parent91 92 def __getitem__(self, key):28 unmodified lines121 self.name122 )123 124 140-class LoopContextBase(object):141- """Helper for extended iteration."""125+class LoopContext(object):126+ """A loop context for dynamic iteration."""127 143- def __init__(self, iterable, parent=None):128+ def __init__(self, iterable, enforce_length=False):129 self._iterable = iterable130+ self._next = iter(iterable).next131 self._length = None146- self.index0 = 0147- self.parent = parent132+ self.index0 = -1133+ if enforce_length:134+ len(self)135 136 def cycle(self, *args):137 """A replacement for the old ``{% cycle %}`` tag."""138 if not args:8 unmodified lines147 148 def __len__(self):149 return self.length150 164-165-class LoopContext(LoopContextBase):166- """A loop context for dynamic iteration."""167-168- def __init__(self, iterable, enforce_length=False):169- self._iterable = iterable170- self._next = iter(iterable).next171- self._length = None172- self.index0 = -1173- if enforce_length:174- len(self)175-176- def make_static(self):177- """Return a static loop context for the optimizer."""178- return StaticLoopContext(self.index0, self.length)179-151 def __iter__(self):152 return self153 154 def next(self):15 unmodified lines170 def __repr__(self):171 return 'LoopContext(%r)' % self.index0172 173 203-class StaticLoopContext(LoopContextBase):204- """The static loop context is used in the optimizer to "freeze" the205- status of an iteration. The only reason for this object is if the206- loop object is accessed in a non static way (eg: becomes part of a207- function call).208- """209-210- def __init__(self, index0, length):211- self.index0 = index0212- self.length = length213-214- def __repr__(self):215- """The repr is used by the optimizer to dump the object."""216- return 'StaticLoopContext(%r, %r)' % (217- self.index0,218- self.length219- )220-221- def make_static(self):222- return self223-224-174 class Macro(object):175 """Wraps a macro."""176 177 def __init__(self, environment, func, name, arguments, defaults,143 unmodified lines