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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
<span id="timeit-measure-execution-time-of-small-code-snippets"></span><h1>timeit — Measure execution time of small code snippets</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/timeit.py">Lib/timeit.py</a></p> <p>This module provides a simple way to time small bits of Python code. It has both a <a class="reference internal" href="#timeit-command-line-interface"><span class="std std-ref">Command-Line Interface</span></a> as well as a <a class="reference internal" href="#python-interface"><span class="std std-ref">callable</span></a> one. It avoids a number of common traps for measuring execution times. See also Tim Peters’ introduction to the “Algorithms” chapter in the second edition of <em>Python Cookbook</em>, published by O’Reilly.</p> <section id="basic-examples"> <h2>Basic Examples</h2> <p>The following example shows how the <a class="reference internal" href="#timeit-command-line-interface"><span class="std std-ref">Command-Line Interface</span></a> can be used to compare three different expressions:</p> <pre data-language="shell">$ python -m timeit "'-'.join(str(n) for n in range(100))"
10000 loops, best of 5: 30.2 usec per loop
$ python -m timeit "'-'.join([str(n) for n in range(100)])"
10000 loops, best of 5: 27.5 usec per loop
$ python -m timeit "'-'.join(map(str, range(100)))"
10000 loops, best of 5: 23.2 usec per loop
</pre> <p>This can be achieved from the <a class="reference internal" href="#python-interface"><span class="std std-ref">Python Interface</span></a> with:</p> <pre data-language="python">>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237
</pre> <p>A callable can also be passed from the <a class="reference internal" href="#python-interface"><span class="std std-ref">Python Interface</span></a>:</p> <pre data-language="python">>>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000)
0.19665591977536678
</pre> <p>Note however that <a class="reference internal" href="#timeit.timeit" title="timeit.timeit"><code>timeit()</code></a> will automatically determine the number of repetitions only when the command-line interface is used. In the <a class="reference internal" href="#timeit-examples"><span class="std std-ref">Examples</span></a> section you can find more advanced examples.</p> </section> <section id="python-interface"> <span id="id1"></span><h2>Python Interface</h2> <p>The module defines three convenience functions and a public class:</p> <dl class="py function"> <dt class="sig sig-object py" id="timeit.timeit">
<code>timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)</code> </dt> <dd>
<p>Create a <a class="reference internal" href="#timeit.Timer" title="timeit.Timer"><code>Timer</code></a> instance with the given statement, <em>setup</em> code and <em>timer</em> function and run its <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a> method with <em>number</em> executions. The optional <em>globals</em> argument specifies a namespace in which to execute the code.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The optional <em>globals</em> parameter was added.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="timeit.repeat">
<code>timeit.repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=5, number=1000000, globals=None)</code> </dt> <dd>
<p>Create a <a class="reference internal" href="#timeit.Timer" title="timeit.Timer"><code>Timer</code></a> instance with the given statement, <em>setup</em> code and <em>timer</em> function and run its <a class="reference internal" href="#timeit.Timer.repeat" title="timeit.Timer.repeat"><code>repeat()</code></a> method with the given <em>repeat</em> count and <em>number</em> executions. The optional <em>globals</em> argument specifies a namespace in which to execute the code.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The optional <em>globals</em> parameter was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Default value of <em>repeat</em> changed from 3 to 5.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="timeit.default_timer">
<code>timeit.default_timer()</code> </dt> <dd>
<p>The default timer, which is always time.perf_counter(), returns float seconds. An alternative, time.perf_counter_ns, returns integer nanoseconds.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span><a class="reference internal" href="time#time.perf_counter" title="time.perf_counter"><code>time.perf_counter()</code></a> is now the default timer.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="timeit.Timer">
<code>class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>, globals=None)</code> </dt> <dd>
<p>Class for timing execution speed of small code snippets.</p> <p>The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to <code>'pass'</code>; the timer function is platform-dependent (see the module doc string). <em>stmt</em> and <em>setup</em> may also contain multiple statements separated by <code>;</code> or newlines, as long as they don’t contain multi-line string literals. The statement will by default be executed within timeit’s namespace; this behavior can be controlled by passing a namespace to <em>globals</em>.</p> <p>To measure the execution time of the first statement, use the <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a> method. The <a class="reference internal" href="#timeit.Timer.repeat" title="timeit.Timer.repeat"><code>repeat()</code></a> and <a class="reference internal" href="#timeit.Timer.autorange" title="timeit.Timer.autorange"><code>autorange()</code></a> methods are convenience methods to call <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a> multiple times.</p> <p>The execution time of <em>setup</em> is excluded from the overall timed execution run.</p> <p>The <em>stmt</em> and <em>setup</em> parameters can also take objects that are callable without arguments. This will embed calls to them in a timer function that will then be executed by <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a>. Note that the timing overhead is a little larger in this case because of the extra function calls.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The optional <em>globals</em> parameter was added.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="timeit.Timer.timeit">
<code>timeit(number=1000000)</code> </dt> <dd>
<p>Time <em>number</em> executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times. The default timer returns seconds as a float. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>By default, <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a> temporarily turns off <a class="reference internal" href="../glossary#term-garbage-collection"><span class="xref std std-term">garbage collection</span></a> during the timing. The advantage of this approach is that it makes independent timings more comparable. The disadvantage is that GC may be an important component of the performance of the function being measured. If so, GC can be re-enabled as the first statement in the <em>setup</em> string. For example:</p> <pre data-language="python">timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
</pre> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="timeit.Timer.autorange">
<code>autorange(callback=None)</code> </dt> <dd>
<p>Automatically determine how many times to call <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a>.</p> <p>This is a convenience function that calls <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a> repeatedly so that the total time >= 0.2 second, returning the eventual (number of loops, time taken for that number of loops). It calls <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a> with increasing numbers from the sequence 1, 2, 5, 10, 20, 50, … until the time taken is at least 0.2 seconds.</p> <p>If <em>callback</em> is given and is not <code>None</code>, it will be called after each trial with two arguments: <code>callback(number, time_taken)</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="timeit.Timer.repeat">
<code>repeat(repeat=5, number=1000000)</code> </dt> <dd>
<p>Call <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a> a few times.</p> <p>This is a convenience function that calls the <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a> repeatedly, returning a list of results. The first argument specifies how many times to call <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a>. The second argument specifies the <em>number</em> argument for <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code>timeit()</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>It’s tempting to calculate mean and standard deviation from the result vector and report these. However, this is not very useful. In a typical case, the lowest value gives a lower bound for how fast your machine can run the given code snippet; higher values in the result vector are typically not caused by variability in Python’s speed, but by other processes interfering with your timing accuracy. So the <a class="reference internal" href="functions#min" title="min"><code>min()</code></a> of the result is probably the only number you should be interested in. After that, you should look at the entire vector and apply common sense rather than statistics.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Default value of <em>repeat</em> changed from 3 to 5.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="timeit.Timer.print_exc">
<code>print_exc(file=None)</code> </dt> <dd>
<p>Helper to print a traceback from the timed code.</p> <p>Typical use:</p> <pre data-language="python">t = Timer(...) # outside the try/except
try:
t.timeit(...) # or t.repeat(...)
except Exception:
t.print_exc()
</pre> <p>The advantage over the standard traceback is that source lines in the compiled template will be displayed. The optional <em>file</em> argument directs where the traceback is sent; it defaults to <a class="reference internal" href="sys#sys.stderr" title="sys.stderr"><code>sys.stderr</code></a>.</p> </dd>
</dl> </dd>
</dl> </section> <section id="command-line-interface"> <span id="timeit-command-line-interface"></span><h2>Command-Line Interface</h2> <p>When called as a program from the command line, the following form is used:</p> <pre data-language="python">python -m timeit [-n N] [-r N] [-u U] [-s S] [-p] [-v] [-h] [statement ...]
</pre> <p>Where the following options are understood:</p> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-timeit-n">
<code>-n N, --number=N</code> </dt> <dd>
<p>how many times to execute ‘statement’</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-timeit-r">
<code>-r N, --repeat=N</code> </dt> <dd>
<p>how many times to repeat the timer (default 5)</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-timeit-s">
<code>-s S, --setup=S</code> </dt> <dd>
<p>statement to be executed once initially (default <code>pass</code>)</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-timeit-p">
<code>-p, --process</code> </dt> <dd>
<p>measure process time, not wallclock time, using <a class="reference internal" href="time#time.process_time" title="time.process_time"><code>time.process_time()</code></a> instead of <a class="reference internal" href="time#time.perf_counter" title="time.perf_counter"><code>time.perf_counter()</code></a>, which is the default</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-timeit-u">
<code>-u, --unit=U</code> </dt> <dd>
<p>specify a time unit for timer output; can select <code>nsec</code>, <code>usec</code>, <code>msec</code>, or <code>sec</code></p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-timeit-v">
<code>-v, --verbose</code> </dt> <dd>
<p>print raw timing results; repeat for more digits precision</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-timeit-h">
<code>-h, --help</code> </dt> <dd>
<p>print a short usage message and exit</p> </dd>
</dl> <p>A multi-line statement may be given by specifying each line as a separate statement argument; indented lines are possible by enclosing an argument in quotes and using leading spaces. Multiple <a class="reference internal" href="#cmdoption-timeit-s"><code>-s</code></a> options are treated similarly.</p> <p>If <a class="reference internal" href="#cmdoption-timeit-n"><code>-n</code></a> is not given, a suitable number of loops is calculated by trying increasing numbers from the sequence 1, 2, 5, 10, 20, 50, … until the total time is at least 0.2 seconds.</p> <p><a class="reference internal" href="#timeit.default_timer" title="timeit.default_timer"><code>default_timer()</code></a> measurements can be affected by other programs running on the same machine, so the best thing to do when accurate timing is necessary is to repeat the timing a few times and use the best time. The <a class="reference internal" href="#cmdoption-timeit-r"><code>-r</code></a> option is good for this; the default of 5 repetitions is probably enough in most cases. You can use <a class="reference internal" href="time#time.process_time" title="time.process_time"><code>time.process_time()</code></a> to measure CPU time.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>There is a certain baseline overhead associated with executing a pass statement. The code here doesn’t try to hide it, but you should be aware of it. The baseline overhead can be measured by invoking the program without arguments, and it might differ between Python versions.</p> </div> </section> <section id="examples"> <span id="timeit-examples"></span><h2>Examples</h2> <p>It is possible to provide a setup statement that is executed only once at the beginning:</p> <pre data-language="shell">$ python -m timeit -s "text = 'sample string'; char = 'g'" "char in text"
5000000 loops, best of 5: 0.0877 usec per loop
$ python -m timeit -s "text = 'sample string'; char = 'g'" "text.find(char)"
1000000 loops, best of 5: 0.342 usec per loop
</pre> <p>In the output, there are three fields. The loop count, which tells you how many times the statement body was run per timing loop repetition. The repetition count (‘best of 5’) which tells you how many times the timing loop was repeated, and finally the time the statement body took on average within the best repetition of the timing loop. That is, the time the fastest repetition took divided by the loop count.</p> <pre data-language="python">>>> import timeit
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
0.41440500499993504
>>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"')
1.7246671520006203
</pre> <p>The same can be done using the <a class="reference internal" href="#timeit.Timer" title="timeit.Timer"><code>Timer</code></a> class and its methods:</p> <pre data-language="python">>>> import timeit
>>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"')
>>> t.timeit()
0.3955516149999312
>>> t.repeat()
[0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886]
</pre> <p>The following examples show how to time expressions that contain multiple lines. Here we compare the cost of using <a class="reference internal" href="functions#hasattr" title="hasattr"><code>hasattr()</code></a> vs. <a class="reference internal" href="../reference/compound_stmts#try"><code>try</code></a>/<a class="reference internal" href="../reference/compound_stmts#except"><code>except</code></a> to test for missing and present object attributes:</p> <pre data-language="shell">$ python -m timeit "try:" " str.__bool__" "except AttributeError:" " pass"
20000 loops, best of 5: 15.7 usec per loop
$ python -m timeit "if hasattr(str, '__bool__'): pass"
50000 loops, best of 5: 4.26 usec per loop
$ python -m timeit "try:" " int.__bool__" "except AttributeError:" " pass"
200000 loops, best of 5: 1.43 usec per loop
$ python -m timeit "if hasattr(int, '__bool__'): pass"
100000 loops, best of 5: 2.23 usec per loop
</pre> <pre data-language="python">>>> import timeit
>>> # attribute is missing
>>> s = """\
... try:
... str.__bool__
... except AttributeError:
... pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.9138244460009446
>>> s = "if hasattr(str, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.5829014980008651
>>>
>>> # attribute is present
>>> s = """\
... try:
... int.__bool__
... except AttributeError:
... pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.04215312199994514
>>> s = "if hasattr(int, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.08588060699912603
</pre> <p>To give the <a class="reference internal" href="#module-timeit" title="timeit: Measure the execution time of small code snippets."><code>timeit</code></a> module access to functions you define, you can pass a <em>setup</em> parameter which contains an import statement:</p> <pre data-language="python">def test():
"""Stupid test function"""
L = [i for i in range(100)]
if __name__ == '__main__':
import timeit
print(timeit.timeit("test()", setup="from __main__ import test"))
</pre> <p>Another option is to pass <a class="reference internal" href="functions#globals" title="globals"><code>globals()</code></a> to the <em>globals</em> parameter, which will cause the code to be executed within your current global namespace. This can be more convenient than individually specifying imports:</p> <pre data-language="python">def f(x):
return x**2
def g(x):
return x**4
def h(x):
return x**8
import timeit
print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals()))
</pre> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/timeit.html" class="_attribution-link">https://docs.python.org/3.12/library/timeit.html</a>
</p>
</div>
|