timeit.py 13 KB

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