MCPcopy Index your code
hub / github.com/RustPython/RustPython / Timer

Class Timer

Lib/timeit.py:83–228  ·  view source on GitHub ↗

Class for timing execution speed of small code snippets. The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to 'pass'; the timer function is platform-dependent (see module doc string). If 'globals' i

Source from the content-addressed store, hash-verified

81
82
83class Timer:
84 """Class for timing execution speed of small code snippets.
85
86 The constructor takes a statement to be timed, an additional
87 statement used for setup, and a timer function. Both statements
88 default to 'pass'; the timer function is platform-dependent (see
89 module doc string). If 'globals' is specified, the code will be
90 executed within that namespace (as opposed to inside timeit's
91 namespace).
92
93 To measure the execution time of the first statement, use the
94 timeit() method. The repeat() method is a convenience to call
95 timeit() multiple times and return a list of results.
96
97 The statements may contain newlines, as long as they don't contain
98 multi-line string literals.
99 """
100
101 def __init__(self, stmt="pass", setup="pass", timer=default_timer,
102 globals=None):
103 """Constructor. See class doc string."""
104 self.timer = timer
105 local_ns = {}
106 global_ns = _globals() if globals is None else globals
107 init = ''
108 if isinstance(setup, str):
109 # Check that the code can be compiled outside a function
110 compile(setup, dummy_src_name, "exec")
111 stmtprefix = setup + '\n'
112 setup = reindent(setup, 4)
113 elif callable(setup):
114 local_ns['_setup'] = setup
115 init += ', _setup=_setup'
116 stmtprefix = ''
117 setup = '_setup()'
118 else:
119 raise ValueError("setup is neither a string nor callable")
120 if isinstance(stmt, str):
121 # Check that the code can be compiled outside a function
122 compile(stmtprefix + stmt, dummy_src_name, "exec")
123 stmt = reindent(stmt, 8)
124 elif callable(stmt):
125 local_ns['_stmt'] = stmt
126 init += ', _stmt=_stmt'
127 stmt = '_stmt()'
128 else:
129 raise ValueError("stmt is neither a string nor callable")
130 src = template.format(stmt=stmt, setup=setup, init=init)
131 self.src = src # Save for traceback display
132 code = compile(src, dummy_src_name, "exec")
133 exec(code, global_ns, local_ns)
134 self.inner = local_ns["inner"]
135
136 def print_exc(self, file=None):
137 """Helper to print a traceback from the timed code.
138
139 Typical use:
140

Callers 3

timeitFunction · 0.70
repeatFunction · 0.70
mainFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected