File: profile_context_manager.py

package info (click to toggle)
python-xmlschema 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 5,208 kB
  • sloc: python: 39,174; xml: 1,282; makefile: 36
file content (81 lines) | stat: -rwxr-xr-x 2,008 bytes parent folder | download
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
#!/usr/bin/env python
#
# Copyright (c), 2022, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Davide Brunato <brunato@sissa.it>
#
from timeit import timeit


def run_timeit(stmt='pass', setup='pass', number=1000):
    seconds = timeit(stmt, setup=setup, number=number)
    print("{}: {}s".format(stmt, seconds))


if __name__ == '__main__':
    from contextlib import contextmanager

    print('*' * 50)
    print("*** Decoder profile for xmlschema package ***")
    print('*' * 50)
    print()

    def func():
        pass

    def inner1():
        yield 1

    def value_from_generator():
        value, = inner1()
        return value

    # inner should not be created again and again
    @contextmanager
    def inner2():
        yield 1

    def value_from_with():
        with inner2() as value:
            return value

    class CM:

        def __init__(self):
            self.level = 0

        def __enter__(self):
            self.level += 1
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            self.level -= 1
            return

    cm = CM()
    level = 10

    def value_from_with2():
        with cm as value:
            return value

    NUMBER = 20000

    print("*** Profile evaluation ***\n")

    setup = 'from __main__ import value_from_with, value_from_with2'
    run_timeit("value_from_with()", setup=setup, number=NUMBER)
    run_timeit("value_from_with2()", setup=setup, number=NUMBER)

    setup = 'from __main__ import cm'
    run_timeit("cm.level += 1; pass; cm.level -= 1", setup=setup, number=NUMBER)

    setup = 'from __main__ import func'
    run_timeit("func()", setup=setup, number=NUMBER)

    setup = 'from __main__ import level'
    run_timeit("level += 1; pass; level -= 1", setup=setup, number=NUMBER)