summaryrefslogtreecommitdiff
path: root/pystache/tests/benchmark.py
blob: d46e973327c611cd6d3a3ff0153f95f1e46c41c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python
# coding: utf-8

"""
A rudimentary backward- and forward-compatible script to benchmark pystache.

Usage:

tests/benchmark.py 10000

"""

import sys
from timeit import Timer

import pystache

# TODO: make the example realistic.

examples = [
    # Test case: 1
    ("""{{#person}}Hi {{name}}{{/person}}""",
    {"person": {"name": "Jon"}},
    "Hi Jon"),

    # Test case: 2
    ("""\
<div class="comments">
<h3>{{header}}</h3>
<ul>
{{#comments}}<li class="comment">
<h5>{{name}}</h5><p>{{body}}</p>
</li>{{/comments}}
</ul>
</div>""",
    {'header': "My Post Comments",
     'comments': [
         {'name': "Joe", 'body': "Thanks for this post!"},
         {'name': "Sam", 'body': "Thanks for this post!"},
         {'name': "Heather", 'body': "Thanks for this post!"},
         {'name': "Kathy", 'body': "Thanks for this post!"},
         {'name': "George", 'body': "Thanks for this post!"}]},
    """\
<div class="comments">
<h3>My Post Comments</h3>
<ul>
<li class="comment">
<h5>Joe</h5><p>Thanks for this post!</p>
</li><li class="comment">
<h5>Sam</h5><p>Thanks for this post!</p>
</li><li class="comment">
<h5>Heather</h5><p>Thanks for this post!</p>
</li><li class="comment">
<h5>Kathy</h5><p>Thanks for this post!</p>
</li><li class="comment">
<h5>George</h5><p>Thanks for this post!</p>
</li>
</ul>
</div>"""),
]


def make_test_function(example):

    template, context, expected = example

    def test():
        actual = pystache.render(template, context)
        if actual != expected:
            raise Exception("Benchmark mismatch: \n%s\n*** != ***\n%s" % (expected, actual))

    return test


def main(sys_argv):
    args = sys_argv[1:]
    count = int(args[0])

    print "Benchmarking: %sx" % count
    print

    for example in examples:

        test = make_test_function(example)

        t = Timer(test,)
        print min(t.repeat(repeat=3, number=count))

    print "Done"


if __name__ == '__main__':
    main(sys.argv)