Skip to content
Myr

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

6 files+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"""6import sys7import cgi8from timeit import Timer9from jinja2 import Environment as JinjaEnvironment1011context = {
235 unmodified lines
247 def test_tenjin():248 from tenjin.helpers import escape, to_str249 tenjin_template.render(context, locals())250251try:252 from spitfire.compiler import util as SpitfireTemplate253 from spitfire.compiler.analyzer import o2_options as spitfire_optimizer254except ImportError:255 test_spitfire = None256else: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})287288 def test_spitfire():289 spitfire_template(search_list=[spitfire_context]).main()290291sys.stdout.write('\r' + '\n'.join((292 '=' * 80,293 'Template Engine BigTable Benchmark'.center(80),253 '-' * 80,294 '=' * 80,295 __doc__,296 '-' * 80297)) + '\n')257for test in 'jinja', 'tenjin', 'mako', 'django', 'genshi', 'cheetah':298for 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))266sys.stdout.write('=' * 80 + '\n')306 sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=20) / 20))307sys.stdout.write('-' * 80 + '\n')308sys.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 lines
78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11from time import time12from copy import copy13from random import randrange14from keyword import iskeyword15from cStringIO import StringIO16from itertools import chain17from jinja2 import nodes18from jinja2.visitor import NodeVisitor, NodeTransformer19from jinja2.exceptions import TemplateAssertionError19from jinja2.runtime import StaticLoopContext, concat20from jinja2.runtime import concat21from jinja2.utils import Markup222324operators = {
28 unmodified lines
53 """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 lines
545 self.name)546 self.blocks[block.name] = block547548 # 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 lines
759 # 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 lines
801 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 lines
909 body[-1].append(const)910 else:911 body.append([const])912912 # 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('))')935936 # otherwise we create a format string as this is faster in that case937 else:938 format = []
44 unmodified lines
983984 # 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)989990 def visit_Name(self, node, frame):991 if node.ctx == 'store':992 if frame.toplevel:
170 unmodified lines
modified:jinja2/debug.py+25 added-3 removed
7 unmodified lines
8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11import sys12from types import CodeType131415def translate_exception(exc_info):16 """If passed an exc_info it will automatically rewrite the exceptions
44 unmodified lines
6162 # and fake the exception63 code = compile('\n' * (lineno - 1) + 'raise __jinja_exception__[0], ' +64 '__jinja_exception__[1]', filename, 'exec')6566 # 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 pass8384 # 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_next9091 # 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)9798 # return without this frame77 return exc_info[:2] + (exc_info[2].tb_next,)99 return exc_info[:2] + (new_tb,)100101102def _init_ugly_crap():103 """This function implements a few ugly things so that we can patch the
68 unmodified lines
modified:jinja2/environment.py+1 added-2 removed
229 unmodified lines
230 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))235236 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 lines
modified:jinja2/parser.py+1 added-2 removed
683 unmodified lines
684 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 lines
modified:jinja2/runtime.py+10 added-61 removed
12 unmodified lines
13from jinja2.exceptions import UndefinedError141516# 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']192021# special singleton representing missing values for the runtime22missing = object()22missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()232425# concatenate a list of strings and convert them to unicode.26concat = u''.join
45 unmodified lines
72 if key in self.parent:73 return self.parent[key]74 return default7576 def setdefault(self, key, default=None):77 """For dict compatibility"""78 self.exported_vars.add(key)79 return self.vars.setdefault(key, default)8081 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)8676 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 lines
85 def get_all(self):86 """Return a copy of the complete context as dict."""87 return dict(self.parent, **self.vars)88100 def __setitem__(self, key, value):101 self.vars[key] = value102 self.exported_vars.add(key)10389 def __contains__(self, name):90 return name in self.vars or name in self.parent9192 def __getitem__(self, key):
28 unmodified lines
121 self.name122 )123124140class LoopContextBase(object):141 """Helper for extended iteration."""125class LoopContext(object):126 """A loop context for dynamic iteration."""127143 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)135136 def cycle(self, *args):137 """A replacement for the old ``{% cycle %}`` tag."""138 if not args:
8 unmodified lines
147148 def __len__(self):149 return self.length150164165class LoopContext(LoopContextBase):166 """A loop context for dynamic iteration."""167168 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)175176 def make_static(self):177 """Return a static loop context for the optimizer."""178 return StaticLoopContext(self.index0, self.length)179151 def __iter__(self):152 return self153154 def next(self):
15 unmodified lines
170 def __repr__(self):171 return 'LoopContext(%r)' % self.index0172173203class 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 """209210 def __init__(self, index0, length):211 self.index0 = index0212 self.length = length213214 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 )220221 def make_static(self):222 return self223224174class Macro(object):175 """Wraps a macro."""176177 def __init__(self, environment, func, name, arguments, defaults,
143 unmodified lines