Benjamin Peterson | 90f5ba5 | 2010-03-11 22:53:45 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python3 |
Skip Montanaro | cfd5550 | 2003-04-08 19:49:40 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 6e31aad | 2003-03-07 01:33:18 +0000 | [diff] [blame] | 3 | """Tool for measuring execution time of small code snippets. |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 4 | |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 5 | This module avoids a number of common traps for measuring execution |
| 6 | times. See also Tim Peters' introduction to the Algorithms chapter in |
| 7 | the Python Cookbook, published by O'Reilly. |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 9 | Library usage: see the Timer class. |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 10 | |
| 11 | Command line usage: |
Victor Stinner | 3d7feb9 | 2016-10-18 17:18:21 +0200 | [diff] [blame] | 12 | python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement] |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 13 | |
| 14 | Options: |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 15 | -n/--number N: how many times to execute 'statement' (default: see below) |
Victor Stinner | 3ef769f | 2018-06-06 17:55:18 +0200 | [diff] [blame] | 16 | -r/--repeat N: how many times to repeat the timer (default 5) |
Andrew Kuchling | 333518e | 2015-04-21 19:43:33 -0400 | [diff] [blame] | 17 | -s/--setup S: statement to be executed once initially (default 'pass'). |
| 18 | Execution time of this setup statement is NOT timed. |
Georg Brandl | c9d77b2 | 2012-05-01 11:56:22 +0200 | [diff] [blame] | 19 | -p/--process: use time.process_time() (default is time.perf_counter()) |
Guido van Rossum | 0070f00 | 2003-03-15 12:25:00 +0000 | [diff] [blame] | 20 | -v/--verbose: print raw timing results; repeat for more digits precision |
Victor Stinner | c3e40f8 | 2016-10-18 17:42:48 +0200 | [diff] [blame] | 21 | -u/--unit: set the output time unit (nsec, usec, msec, or sec) |
Guido van Rossum | e8577b7 | 2003-03-06 03:02:10 +0000 | [diff] [blame] | 22 | -h/--help: print this usage message and exit |
Georg Brandl | 794f5b3 | 2010-08-01 08:52:32 +0000 | [diff] [blame] | 23 | --: separate options from statement, use when statement starts with - |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 24 | statement: statement to be timed (default 'pass') |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 25 | |
| 26 | A multi-line statement may be given by specifying each line as a |
| 27 | separate argument; indented lines are possible by enclosing an |
Guido van Rossum | 6e31aad | 2003-03-07 01:33:18 +0000 | [diff] [blame] | 28 | argument in quotes and using leading spaces. Multiple -s options are |
| 29 | treated similarly. |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 30 | |
| 31 | If -n is not given, a suitable number of loops is calculated by trying |
| 32 | successive powers of 10 until the total time is at least 0.2 seconds. |
| 33 | |
Guido van Rossum | e8577b7 | 2003-03-06 03:02:10 +0000 | [diff] [blame] | 34 | Note: there is a certain baseline overhead associated with executing a |
Terry Jan Reedy | d49af5d | 2013-03-15 03:04:25 -0400 | [diff] [blame] | 35 | pass statement. It differs between versions. The code here doesn't try |
| 36 | to hide it, but you should be aware of it. The baseline overhead can be |
| 37 | measured by invoking the program without arguments. |
Guido van Rossum | 6e31aad | 2003-03-07 01:33:18 +0000 | [diff] [blame] | 38 | |
Terry Jan Reedy | d49af5d | 2013-03-15 03:04:25 -0400 | [diff] [blame] | 39 | Classes: |
| 40 | |
| 41 | Timer |
| 42 | |
| 43 | Functions: |
| 44 | |
| 45 | timeit(string, string) -> float |
| 46 | repeat(string, string) -> list |
| 47 | default_timer() -> float |
| 48 | |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 49 | """ |
| 50 | |
Raymond Hettinger | 816ed1b | 2004-01-04 03:47:51 +0000 | [diff] [blame] | 51 | import gc |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 52 | import sys |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 53 | import time |
Terry Jan Reedy | d49af5d | 2013-03-15 03:04:25 -0400 | [diff] [blame] | 54 | import itertools |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 55 | |
Terry Jan Reedy | d49af5d | 2013-03-15 03:04:25 -0400 | [diff] [blame] | 56 | __all__ = ["Timer", "timeit", "repeat", "default_timer"] |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 57 | |
Guido van Rossum | 538f1d8 | 2003-03-14 17:21:00 +0000 | [diff] [blame] | 58 | dummy_src_name = "<timeit-src>" |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 59 | default_number = 1000000 |
Victor Stinner | 1b90115 | 2016-10-18 17:13:22 +0200 | [diff] [blame] | 60 | default_repeat = 5 |
Victor Stinner | fe98e2f | 2012-04-29 03:01:20 +0200 | [diff] [blame] | 61 | default_timer = time.perf_counter |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 62 | |
Antoine Pitrou | ef3b9ed | 2014-08-22 23:13:50 -0400 | [diff] [blame] | 63 | _globals = globals |
| 64 | |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 65 | # Don't change the indentation of the template; the reindent() calls |
| 66 | # in Timer.__init__() depend on setup being indented 4 spaces and stmt |
| 67 | # being indented 8 spaces. |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 68 | template = """ |
Serhiy Storchaka | f28fa66 | 2015-05-30 19:38:26 +0300 | [diff] [blame] | 69 | def inner(_it, _timer{init}): |
Raymond Hettinger | c800af4 | 2011-04-04 09:28:25 -0700 | [diff] [blame] | 70 | {setup} |
Guido van Rossum | 538f1d8 | 2003-03-14 17:21:00 +0000 | [diff] [blame] | 71 | _t0 = _timer() |
Guido van Rossum | dd42edc | 2003-03-21 14:54:19 +0000 | [diff] [blame] | 72 | for _i in _it: |
Raymond Hettinger | c800af4 | 2011-04-04 09:28:25 -0700 | [diff] [blame] | 73 | {stmt} |
Guido van Rossum | 538f1d8 | 2003-03-14 17:21:00 +0000 | [diff] [blame] | 74 | _t1 = _timer() |
| 75 | return _t1 - _t0 |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 76 | """ |
| 77 | |
| 78 | def reindent(src, indent): |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 79 | """Helper to reindent a multi-line statement.""" |
Guido van Rossum | e05dcce | 2003-03-06 13:09:09 +0000 | [diff] [blame] | 80 | return src.replace("\n", "\n" + " "*indent) |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 81 | |
| 82 | class Timer: |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 83 | """Class for timing execution speed of small code snippets. |
| 84 | |
| 85 | The constructor takes a statement to be timed, an additional |
| 86 | statement used for setup, and a timer function. Both statements |
| 87 | default to 'pass'; the timer function is platform-dependent (see |
Antoine Pitrou | ef3b9ed | 2014-08-22 23:13:50 -0400 | [diff] [blame] | 88 | module doc string). If 'globals' is specified, the code will be |
| 89 | executed within that namespace (as opposed to inside timeit's |
| 90 | namespace). |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 91 | |
| 92 | To measure the execution time of the first statement, use the |
| 93 | timeit() method. The repeat() method is a convenience to call |
| 94 | timeit() multiple times and return a list of results. |
| 95 | |
| 96 | The statements may contain newlines, as long as they don't contain |
| 97 | multi-line string literals. |
| 98 | """ |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 99 | |
Antoine Pitrou | ef3b9ed | 2014-08-22 23:13:50 -0400 | [diff] [blame] | 100 | def __init__(self, stmt="pass", setup="pass", timer=default_timer, |
| 101 | globals=None): |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 102 | """Constructor. See class doc string.""" |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 103 | self.timer = timer |
Antoine Pitrou | ef3b9ed | 2014-08-22 23:13:50 -0400 | [diff] [blame] | 104 | local_ns = {} |
| 105 | global_ns = _globals() if globals is None else globals |
Serhiy Storchaka | 1b560cb | 2015-05-30 19:44:55 +0300 | [diff] [blame] | 106 | init = '' |
| 107 | if isinstance(setup, str): |
| 108 | # Check that the code can be compiled outside a function |
| 109 | compile(setup, dummy_src_name, "exec") |
Serhiy Storchaka | ced770d | 2015-07-15 22:11:36 +0300 | [diff] [blame] | 110 | stmtprefix = setup + '\n' |
Serhiy Storchaka | 1b560cb | 2015-05-30 19:44:55 +0300 | [diff] [blame] | 111 | setup = reindent(setup, 4) |
| 112 | elif callable(setup): |
| 113 | local_ns['_setup'] = setup |
| 114 | init += ', _setup=_setup' |
Serhiy Storchaka | ced770d | 2015-07-15 22:11:36 +0300 | [diff] [blame] | 115 | stmtprefix = '' |
Serhiy Storchaka | 1b560cb | 2015-05-30 19:44:55 +0300 | [diff] [blame] | 116 | setup = '_setup()' |
| 117 | else: |
| 118 | raise ValueError("setup is neither a string nor callable") |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 119 | if isinstance(stmt, str): |
Serhiy Storchaka | 2bef585 | 2015-01-26 12:09:17 +0200 | [diff] [blame] | 120 | # Check that the code can be compiled outside a function |
Serhiy Storchaka | ced770d | 2015-07-15 22:11:36 +0300 | [diff] [blame] | 121 | compile(stmtprefix + stmt, dummy_src_name, "exec") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 122 | stmt = reindent(stmt, 8) |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 123 | elif callable(stmt): |
Serhiy Storchaka | 1b560cb | 2015-05-30 19:44:55 +0300 | [diff] [blame] | 124 | local_ns['_stmt'] = stmt |
| 125 | init += ', _stmt=_stmt' |
| 126 | stmt = '_stmt()' |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 127 | else: |
| 128 | raise ValueError("stmt is neither a string nor callable") |
Serhiy Storchaka | 1b560cb | 2015-05-30 19:44:55 +0300 | [diff] [blame] | 129 | src = template.format(stmt=stmt, setup=setup, init=init) |
| 130 | self.src = src # Save for traceback display |
| 131 | code = compile(src, dummy_src_name, "exec") |
| 132 | exec(code, global_ns, local_ns) |
| 133 | self.inner = local_ns["inner"] |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 134 | |
Guido van Rossum | 538f1d8 | 2003-03-14 17:21:00 +0000 | [diff] [blame] | 135 | def print_exc(self, file=None): |
| 136 | """Helper to print a traceback from the timed code. |
| 137 | |
| 138 | Typical use: |
| 139 | |
| 140 | t = Timer(...) # outside the try/except |
| 141 | try: |
| 142 | t.timeit(...) # or t.repeat(...) |
| 143 | except: |
| 144 | t.print_exc() |
| 145 | |
| 146 | The advantage over the standard traceback is that source lines |
| 147 | in the compiled template will be displayed. |
| 148 | |
| 149 | The optional file argument directs where the traceback is |
| 150 | sent; it defaults to sys.stderr. |
| 151 | """ |
| 152 | import linecache, traceback |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 153 | if self.src is not None: |
| 154 | linecache.cache[dummy_src_name] = (len(self.src), |
| 155 | None, |
| 156 | self.src.split("\n"), |
| 157 | dummy_src_name) |
| 158 | # else the source is already stored somewhere else |
| 159 | |
Guido van Rossum | 538f1d8 | 2003-03-14 17:21:00 +0000 | [diff] [blame] | 160 | traceback.print_exc(file=file) |
| 161 | |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 162 | def timeit(self, number=default_number): |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 163 | """Time 'number' executions of the main statement. |
| 164 | |
| 165 | To be precise, this executes the setup statement once, and |
| 166 | then returns the time it takes to execute the main statement |
| 167 | a number of times, as a float measured in seconds. The |
| 168 | argument is the number of times through the loop, defaulting |
| 169 | to one million. The main statement, the setup statement and |
| 170 | the timer function to be used are passed to the constructor. |
| 171 | """ |
Terry Jan Reedy | d49af5d | 2013-03-15 03:04:25 -0400 | [diff] [blame] | 172 | it = itertools.repeat(None, number) |
Raymond Hettinger | 816ed1b | 2004-01-04 03:47:51 +0000 | [diff] [blame] | 173 | gcold = gc.isenabled() |
| 174 | gc.disable() |
Raymond Hettinger | 3a081f5 | 2011-07-29 00:02:04 -0700 | [diff] [blame] | 175 | try: |
| 176 | timing = self.inner(it, self.timer) |
| 177 | finally: |
| 178 | if gcold: |
| 179 | gc.enable() |
Raymond Hettinger | 816ed1b | 2004-01-04 03:47:51 +0000 | [diff] [blame] | 180 | return timing |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 181 | |
| 182 | def repeat(self, repeat=default_repeat, number=default_number): |
Skip Montanaro | fb2a6cc | 2003-04-08 19:40:19 +0000 | [diff] [blame] | 183 | """Call timeit() a few times. |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 184 | |
Skip Montanaro | fb2a6cc | 2003-04-08 19:40:19 +0000 | [diff] [blame] | 185 | This is a convenience function that calls the timeit() |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 186 | repeatedly, returning a list of results. The first argument |
Victor Stinner | 3ef769f | 2018-06-06 17:55:18 +0200 | [diff] [blame] | 187 | specifies how many times to call timeit(), defaulting to 5; |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 188 | the second argument specifies the timer argument, defaulting |
| 189 | to one million. |
Guido van Rossum | 5573541 | 2003-03-06 16:11:17 +0000 | [diff] [blame] | 190 | |
| 191 | Note: it's tempting to calculate mean and standard deviation |
| 192 | from the result vector and report these. However, this is not |
| 193 | very useful. In a typical case, the lowest value gives a |
| 194 | lower bound for how fast your machine can run the given code |
| 195 | snippet; higher values in the result vector are typically not |
| 196 | caused by variability in Python's speed, but by other |
| 197 | processes interfering with your timing accuracy. So the min() |
| 198 | of the result is probably the only number you should be |
| 199 | interested in. After that, you should look at the entire |
| 200 | vector and apply common sense rather than statistics. |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 201 | """ |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 202 | r = [] |
| 203 | for i in range(repeat): |
| 204 | t = self.timeit(number) |
| 205 | r.append(t) |
| 206 | return r |
| 207 | |
Steven D'Aprano | 09f4f71 | 2016-08-15 01:27:03 +1000 | [diff] [blame] | 208 | def autorange(self, callback=None): |
Xiang Zhang | ecf39bb | 2017-02-28 11:06:07 +0800 | [diff] [blame] | 209 | """Return the number of loops and time taken so that total time >= 0.2. |
Steven D'Aprano | 09f4f71 | 2016-08-15 01:27:03 +1000 | [diff] [blame] | 210 | |
Serhiy Storchaka | d3ff784 | 2016-10-23 15:17:05 +0300 | [diff] [blame] | 211 | Calls the timeit method with increasing numbers from the sequence |
| 212 | 1, 2, 5, 10, 20, 50, ... until the time taken is at least 0.2 |
| 213 | second. Returns (number, time_taken). |
Steven D'Aprano | 09f4f71 | 2016-08-15 01:27:03 +1000 | [diff] [blame] | 214 | |
| 215 | If *callback* is given and is not None, it will be called after |
| 216 | each trial with two arguments: ``callback(number, time_taken)``. |
| 217 | """ |
Serhiy Storchaka | d3ff784 | 2016-10-23 15:17:05 +0300 | [diff] [blame] | 218 | i = 1 |
| 219 | while True: |
| 220 | for j in 1, 2, 5: |
| 221 | number = i * j |
| 222 | time_taken = self.timeit(number) |
| 223 | if callback: |
| 224 | callback(number, time_taken) |
| 225 | if time_taken >= 0.2: |
| 226 | return (number, time_taken) |
| 227 | i *= 10 |
Steven D'Aprano | 09f4f71 | 2016-08-15 01:27:03 +1000 | [diff] [blame] | 228 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 229 | def timeit(stmt="pass", setup="pass", timer=default_timer, |
Antoine Pitrou | ef3b9ed | 2014-08-22 23:13:50 -0400 | [diff] [blame] | 230 | number=default_number, globals=None): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 231 | """Convenience function to create Timer object and call timeit method.""" |
Antoine Pitrou | ef3b9ed | 2014-08-22 23:13:50 -0400 | [diff] [blame] | 232 | return Timer(stmt, setup, timer, globals).timeit(number) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 233 | |
| 234 | def repeat(stmt="pass", setup="pass", timer=default_timer, |
Antoine Pitrou | ef3b9ed | 2014-08-22 23:13:50 -0400 | [diff] [blame] | 235 | repeat=default_repeat, number=default_number, globals=None): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 236 | """Convenience function to create Timer object and call repeat method.""" |
Antoine Pitrou | ef3b9ed | 2014-08-22 23:13:50 -0400 | [diff] [blame] | 237 | return Timer(stmt, setup, timer, globals).repeat(repeat, number) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 238 | |
R David Murray | a88da67 | 2011-03-16 17:32:27 -0400 | [diff] [blame] | 239 | def main(args=None, *, _wrap_timer=None): |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 240 | """Main program, used when run as a script. |
| 241 | |
R David Murray | a88da67 | 2011-03-16 17:32:27 -0400 | [diff] [blame] | 242 | The optional 'args' argument specifies the command line to be parsed, |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 243 | defaulting to sys.argv[1:]. |
| 244 | |
| 245 | The return value is an exit code to be passed to sys.exit(); it |
| 246 | may be None to indicate success. |
Guido van Rossum | 538f1d8 | 2003-03-14 17:21:00 +0000 | [diff] [blame] | 247 | |
| 248 | When an exception happens during timing, a traceback is printed to |
| 249 | stderr and the return value is 1. Exceptions at other times |
| 250 | (including the template compilation) are not caught. |
R David Murray | a88da67 | 2011-03-16 17:32:27 -0400 | [diff] [blame] | 251 | |
| 252 | '_wrap_timer' is an internal interface used for unit testing. If it |
| 253 | is not None, it must be a callable that accepts a timer function |
| 254 | and returns another timer function (used for unit testing). |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 255 | """ |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 256 | if args is None: |
| 257 | args = sys.argv[1:] |
| 258 | import getopt |
| 259 | try: |
Robert Collins | 302dbc6 | 2015-03-18 09:54:50 +1300 | [diff] [blame] | 260 | opts, args = getopt.getopt(args, "n:u:s:r:tcpvh", |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 261 | ["number=", "setup=", "repeat=", |
Georg Brandl | c9d77b2 | 2012-05-01 11:56:22 +0200 | [diff] [blame] | 262 | "time", "clock", "process", |
Robert Collins | 302dbc6 | 2015-03-18 09:54:50 +1300 | [diff] [blame] | 263 | "verbose", "unit=", "help"]) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 264 | except getopt.error as err: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 265 | print(err) |
| 266 | print("use -h/--help for command line help") |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 267 | return 2 |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 268 | |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 269 | timer = default_timer |
| 270 | stmt = "\n".join(args) or "pass" |
| 271 | number = 0 # auto-determine |
Guido van Rossum | 6e31aad | 2003-03-07 01:33:18 +0000 | [diff] [blame] | 272 | setup = [] |
Guido van Rossum | 0070f00 | 2003-03-15 12:25:00 +0000 | [diff] [blame] | 273 | repeat = default_repeat |
| 274 | verbose = 0 |
Robert Collins | 302dbc6 | 2015-03-18 09:54:50 +1300 | [diff] [blame] | 275 | time_unit = None |
Victor Stinner | c3e40f8 | 2016-10-18 17:42:48 +0200 | [diff] [blame] | 276 | units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0} |
Guido van Rossum | 0070f00 | 2003-03-15 12:25:00 +0000 | [diff] [blame] | 277 | precision = 3 |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 278 | for o, a in opts: |
| 279 | if o in ("-n", "--number"): |
| 280 | number = int(a) |
| 281 | if o in ("-s", "--setup"): |
Guido van Rossum | 6e31aad | 2003-03-07 01:33:18 +0000 | [diff] [blame] | 282 | setup.append(a) |
Robert Collins | 302dbc6 | 2015-03-18 09:54:50 +1300 | [diff] [blame] | 283 | if o in ("-u", "--unit"): |
| 284 | if a in units: |
| 285 | time_unit = a |
| 286 | else: |
Victor Stinner | c3e40f8 | 2016-10-18 17:42:48 +0200 | [diff] [blame] | 287 | print("Unrecognized unit. Please select nsec, usec, msec, or sec.", |
Robert Collins | 302dbc6 | 2015-03-18 09:54:50 +1300 | [diff] [blame] | 288 | file=sys.stderr) |
| 289 | return 2 |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 290 | if o in ("-r", "--repeat"): |
| 291 | repeat = int(a) |
| 292 | if repeat <= 0: |
| 293 | repeat = 1 |
Georg Brandl | c9d77b2 | 2012-05-01 11:56:22 +0200 | [diff] [blame] | 294 | if o in ("-p", "--process"): |
| 295 | timer = time.process_time |
Guido van Rossum | 0070f00 | 2003-03-15 12:25:00 +0000 | [diff] [blame] | 296 | if o in ("-v", "--verbose"): |
| 297 | if verbose: |
| 298 | precision += 1 |
| 299 | verbose += 1 |
Guido van Rossum | e8577b7 | 2003-03-06 03:02:10 +0000 | [diff] [blame] | 300 | if o in ("-h", "--help"): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 301 | print(__doc__, end=' ') |
Guido van Rossum | e8577b7 | 2003-03-06 03:02:10 +0000 | [diff] [blame] | 302 | return 0 |
Guido van Rossum | 6e31aad | 2003-03-07 01:33:18 +0000 | [diff] [blame] | 303 | setup = "\n".join(setup) or "pass" |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 304 | |
Raymond Hettinger | 22952a3 | 2003-05-20 04:59:56 +0000 | [diff] [blame] | 305 | # Include the current directory, so that local imports work (sys.path |
| 306 | # contains the directory of this script, rather than the current |
| 307 | # directory) |
| 308 | import os |
| 309 | sys.path.insert(0, os.curdir) |
R David Murray | a88da67 | 2011-03-16 17:32:27 -0400 | [diff] [blame] | 310 | if _wrap_timer is not None: |
| 311 | timer = _wrap_timer(timer) |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 312 | |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 313 | t = Timer(stmt, setup, timer) |
| 314 | if number == 0: |
| 315 | # determine number so that 0.2 <= total time < 2.0 |
Steven D'Aprano | 09f4f71 | 2016-08-15 01:27:03 +1000 | [diff] [blame] | 316 | callback = None |
| 317 | if verbose: |
| 318 | def callback(number, time_taken): |
Victor Stinner | f8fb82c | 2016-10-18 17:06:56 +0200 | [diff] [blame] | 319 | msg = "{num} loop{s} -> {secs:.{prec}g} secs" |
| 320 | plural = (number != 1) |
| 321 | print(msg.format(num=number, s='s' if plural else '', |
| 322 | secs=time_taken, prec=precision)) |
Steven D'Aprano | 09f4f71 | 2016-08-15 01:27:03 +1000 | [diff] [blame] | 323 | try: |
| 324 | number, _ = t.autorange(callback) |
| 325 | except: |
| 326 | t.print_exc() |
| 327 | return 1 |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 328 | |
Victor Stinner | 62cca92 | 2016-10-18 17:55:18 +0200 | [diff] [blame] | 329 | if verbose: |
| 330 | print() |
| 331 | |
Guido van Rossum | 538f1d8 | 2003-03-14 17:21:00 +0000 | [diff] [blame] | 332 | try: |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 333 | raw_timings = t.repeat(repeat, number) |
Guido van Rossum | 538f1d8 | 2003-03-14 17:21:00 +0000 | [diff] [blame] | 334 | except: |
| 335 | t.print_exc() |
| 336 | return 1 |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 337 | |
| 338 | def format_time(dt): |
| 339 | unit = time_unit |
| 340 | |
| 341 | if unit is not None: |
| 342 | scale = units[unit] |
| 343 | else: |
| 344 | scales = [(scale, unit) for unit, scale in units.items()] |
| 345 | scales.sort(reverse=True) |
| 346 | for scale, unit in scales: |
| 347 | if dt >= scale: |
| 348 | break |
| 349 | |
| 350 | return "%.*g %s" % (precision, dt / scale, unit) |
| 351 | |
Guido van Rossum | 0070f00 | 2003-03-15 12:25:00 +0000 | [diff] [blame] | 352 | if verbose: |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 353 | print("raw times: %s" % ", ".join(map(format_time, raw_timings))) |
Victor Stinner | 62cca92 | 2016-10-18 17:55:18 +0200 | [diff] [blame] | 354 | print() |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 355 | timings = [dt / number for dt in raw_timings] |
| 356 | |
| 357 | best = min(timings) |
| 358 | print("%d loop%s, best of %d: %s per loop" |
| 359 | % (number, 's' if number != 1 else '', |
| 360 | repeat, format_time(best))) |
| 361 | |
| 362 | best = min(timings) |
| 363 | worst = max(timings) |
Robert Collins | 69de2a5 | 2015-08-26 12:40:28 +1200 | [diff] [blame] | 364 | if worst >= best * 4: |
Robert Collins | 69de2a5 | 2015-08-26 12:40:28 +1200 | [diff] [blame] | 365 | import warnings |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 366 | warnings.warn_explicit("The test results are likely unreliable. " |
| 367 | "The worst time (%s) was more than four times " |
| 368 | "slower than the best time (%s)." |
Victor Stinner | af48a91 | 2016-10-19 15:48:23 +0200 | [diff] [blame] | 369 | % (format_time(worst), format_time(best)), |
Victor Stinner | 61de57f | 2016-10-18 17:56:42 +0200 | [diff] [blame] | 370 | UserWarning, '', 0) |
Guido van Rossum | b7ab600 | 2003-03-06 02:32:19 +0000 | [diff] [blame] | 371 | return None |
Guido van Rossum | b3f09d4 | 2003-03-05 23:31:58 +0000 | [diff] [blame] | 372 | |
| 373 | if __name__ == "__main__": |
| 374 | sys.exit(main()) |