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