Skip to content
Myr

bench.py

This file

Path

examples/bench.py

319 lines · 8.0 KiB · Python

Last changed by

Unified some code in the super/template reference system.Armin Ronacherbefore adoptionc347ed0

History of this file

Take it

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.\5"""6import sys7import cgi8from timeit import Timer9from jinja2 import Environment as JinjaEnvironment1011context = {12    'page_title': 'mitsuhiko\'s benchmark',13    'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)]14}1516jinja_template = JinjaEnvironment(17    line_statement_prefix='%',18    variable_start_string="${",19    variable_end_string="}"20).from_string("""\21<!doctype html>22<html>23  <head>24    <title>${page_title|e}</title>25  </head>26  <body>27    <div class="header">28      <h1>${page_title|e}</h1>29    </div>30    <ul class="navigation">31    % for href, caption in [32        ('index.html', 'Index'),33        ('downloads.html', 'Downloads'),34        ('products.html', 'Products')35      ]36      <li><a href="${href|e}">${caption|e}</a></li>37    % endfor38    </ul>39    <div class="table">40      <table>41      % for row in table42        <tr>43        % for cell in row44          <td>${cell}</td>45        % endfor46        </tr>47      % endfor48      </table>49    </div>50  </body>51</html>\52""")5354def test_jinja():55    jinja_template.render(context)5657try:58    from django.conf import settings59    settings.configure()60    from django.template import Template as DjangoTemplate, Context as DjangoContext61except ImportError:62    test_django = None63else:64    django_template = """\65<!doctype html>66<html>67  <head>68    <title>{{ page_title }}</title>69  </head>70  <body>71    <div class="header">72      <h1>{{ page_title }}</h1>73    </div>74    <ul class="navigation">75    {% for href, caption in navigation %}76      <li><a href="{{ href }}">{{ caption }}</a></li>77    {% endfor %}78    </ul>79    <div class="table">80      <table>81      {% for row in table %}82        <tr>83        {% for cell in row %}84          <td>{{ cell }}</td>85        {% endfor %}86        </tr>87      {% endfor %}88      </table>89    </div>90  </body>91</html>\92"""9394    def test_django():95        c = DjangoContext(context)96        c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'),97                           ('products.html', 'Products')]98        # recompile template each rendering because that's what django99        # is doing in normal situations too.  Django is not thread safe100        # so we can't cache it in regular apps either.101        DjangoTemplate(django_template).render(c)102103try:104    from mako.template import Template as MakoTemplate105except ImportError:106    test_mako = None107else:108    mako_template = MakoTemplate("""\109<!doctype html>110<html>111  <head>112    <title>${page_title|h}</title>113  </head>114  <body>115    <div class="header">116      <h1>${page_title|h}</h1>117    </div>118    <ul class="navigation">119    % for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]:120      <li><a href="${href|h}">${caption|h}</a></li>121    % endfor122    </ul>123    <div class="table">124      <table>125      % for row in table:126        <tr>127        % for cell in row:128          <td>${cell}</td>129        % endfor130        </tr>131      % endfor132      </table>133    </div>134  </body>135</html>\136""")137138    def test_mako():139        mako_template.render(**context)140141try:142    from genshi.template import MarkupTemplate as GenshiTemplate143except ImportError:144    test_genshi = None145else:146    genshi_template = GenshiTemplate("""\147<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">148  <head>149    <title>${page_title}</title>150  </head>151  <body>152    <div class="header">153      <h1>${page_title}</h1>154    </div>155    <ul class="navigation">156      <li py:for="href, caption in [157        ('index.html', 'Index'),158        ('downloads.html', 'Downloads'),159        ('products.html', 'Products')]"><a href="${href}">${caption}</a></li>160    </ul>161    <div class="table">162      <table>163        <tr py:for="row in table">164          <td py:for="cell in row">${cell}</td>165        </tr>166      </table>167    </div>168  </body>169</html>\170""")171172    def test_genshi():173        genshi_template.generate(**context).render('html', strip_whitespace=False)174175try:176    from Cheetah.Template import Template as CheetahTemplate177except ImportError:178    test_cheetah = None179else:180    cheetah_template = CheetahTemplate("""\181#import cgi182<!doctype html>183<html>184  <head>185    <title>$cgi.escape($page_title)</title>186  </head>187  <body>188    <div class="header">189      <h1>$cgi.escape($page_title)</h1>190    </div>191    <ul class="navigation">192    #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]:193      <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li>194    #end for195    </ul>196    <div class="table">197      <table>198      #for $row in $table:199        <tr>200        #for $cell in $row:201          <td>$cell</td>202        #end for203        </tr>204      #end for205      </table>206    </div>207  </body>208</html>\209""", searchList=[dict(context)])210211    def test_cheetah():212        unicode(cheetah_template)213214try:215    import tenjin216except ImportError:217    test_tenjin = None218else:219    tenjin_template = tenjin.Template()220    tenjin_template.convert("""\221<!doctype html>222<html>223  <head>224    <title>${page_title}</title>225  </head>226  <body>227    <div class="header">228      <h1>${page_title}</h1>229    </div>230    <ul class="navigation">231<?py for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]: ?>232      <li><a href="${href}">${caption}</a></li>233<?py #end ?>234    </ul>235    <div class="table">236      <table>237<?py for row in table: ?>238        <tr>239<?py     for cell in row: ?>240          <td>#{cell}</td>241<?py #end ?>242        </tr>243<?py #end ?>244      </table>245    </div>246  </body>247</html>\248""")249250    def test_tenjin():251        from tenjin.helpers import escape, to_str252        tenjin_template.render(context, locals())253254try:255    from spitfire.compiler import util as SpitfireTemplate256    from spitfire.compiler.analyzer import o2_options as spitfire_optimizer257except ImportError:258    test_spitfire = None259else:260    spitfire_template = SpitfireTemplate.load_template("""\261<!doctype html>262<html>263  <head>264    <title>$cgi.escape($page_title)</title>265  </head>266  <body>267    <div class="header">268      <h1>$cgi.escape($page_title)</h1>269    </div>270    <ul class="navigation">271    #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]272      <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li>273    #end for274    </ul>275    <div class="table">276      <table>277      #for $row in $table278        <tr>279        #for $cell in $row280          <td>$cell</td>281        #end for282        </tr>283      #end for284      </table>285    </div>286  </body>287</html>\288""", 'spitfire_tmpl', spitfire_optimizer, {'enable_filters': False})289    spitfire_context = dict(context, **{'cgi': cgi})290291    def test_spitfire():292        spitfire_template(search_list=[spitfire_context]).main()293294sys.stdout.write('\r' + '\n'.join((295    '=' * 80,296    'Template Engine BigTable Benchmark'.center(80),297    '=' * 80,298    __doc__,299    '-' * 80300)) + '\n')301302303for test in 'jinja', 'mako', 'tenjin', 'spitfire', 'django', 'genshi', 'cheetah':304    if locals()['test_' + test] is None:305        sys.stdout.write('    %-20s*not installed*\n' % test)306        continue307    t = Timer(setup='from __main__ import test_%s as bench' % test,308              stmt='bench()')309    sys.stdout.write(' >> %-20s<running>' % test)310    sys.stdout.flush()311    sys.stdout.write('\r    %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50))312sys.stdout.write('-' * 80 + '\n')313sys.stdout.write('''\314    WARNING: The results of this benchmark are useless to compare the315    performance of template engines and should not be taken seriously in any316    way.  It's testing the performance of simple loops and has no real-world317    usefulnes.  It only used to check if changes on the Jinja code affect318    performance in a good or bad way and how it roughly compares to others.319''' + '=' * 80 + '\n')