/snap/core20/2769/usr/lib/python3.8
NameSizeModeActions
asyncio/-0755rm
collections/-0755rm
concurrent/-0755rm
ctypes/-0755rm
curses/-0755rm
dbm/-0755rm
distutils/-0755rm
email/-0755rm
encodings/-0755rm
html/-0755rm
http/-0755rm
importlib/-0755rm
json/-0755rm
lib-dynload/-0755rm
lib2to3/-0755rm
logging/-0755rm
multiprocessing/-0755rm
pydoc_data/-0755rm
sqlite3/-0755rm
test/-0755rm
unittest/-0755rm
urllib/-0755rm
venv/-0755rm
wsgiref/-0755rm
xml/-0755rm
xmlrpc/-0755rm
__pycache__/-0755rm
abc.py44890644editdlrm
aifc.py328140644editdlrm
antigravity.py4770644editdlrm
argparse.py963110644editdlrm
ast.py192340644editdlrm
asynchat.py113280644editdlrm
asyncore.py200940644editdlrm
base64.py203820755editdlrm
bdb.py320560644editdlrm
binhex.py139540644editdlrm
bisect.py22140644editdlrm
bz2.py125580644editdlrm
calendar.py248320644editdlrm
cgi.py339320755editdlrm
cgitb.py120960644editdlrm
chunk.py54350644editdlrm
cmd.py148600644editdlrm
code.py106220644editdlrm
codecs.py366670644editdlrm
codeop.py63300644editdlrm
colorsys.py40640644editdlrm
compileall.py136780644editdlrm
configparser.py543740644editdlrm
contextlib.py249950644editdlrm
contextvars.py1290644editdlrm
copy.py86610644editdlrm
copyreg.py71350644editdlrm
cProfile.py69980755editdlrm
crypt.py36100644editdlrm
csv.py161440644editdlrm
dataclasses.py499730644editdlrm
datetime.py882870644editdlrm
decimal.py3200644editdlrm
difflib.py840580644editdlrm
dis.py205700644editdlrm
doctest.py1045430644editdlrm
dummy_threading.py28150644editdlrm
enum.py381360644editdlrm
filecmp.py98300644editdlrm
fileinput.py147090644editdlrm
fnmatch.py40790644editdlrm
formatter.py151430644editdlrm
fractions.py243290644editdlrm
ftplib.py351290644editdlrm
functools.py374060644editdlrm
genericpath.py49750644editdlrm
getopt.py74890644editdlrm
getpass.py59940644editdlrm
gettext.py275650644editdlrm
glob.py56970644editdlrm
gzip.py214130644editdlrm
hashlib.py97300644editdlrm
heapq.py228770644editdlrm
hmac.py66290644editdlrm
imaplib.py537750644editdlrm
imghdr.py38080644editdlrm
imp.py105360644editdlrm
inspect.py1185500644editdlrm
io.py35410644editdlrm
ipaddress.py763360644editdlrm
keyword.py9450644editdlrm
LICENSE.txt139250644editdlrm
linecache.py53300644editdlrm
locale.py781950644editdlrm
lzma.py129830644editdlrm
mailbox.py786610644editdlrm
mailcap.py90670644editdlrm
mimetypes.py216640644editdlrm
modulefinder.py244300644editdlrm
netrc.py55660644editdlrm
nntplib.py432610644editdlrm
ntpath.py258140644editdlrm
nturl2path.py28870644editdlrm
numbers.py102440644editdlrm
opcode.py58080644editdlrm
operator.py107110644editdlrm
optparse.py603690644editdlrm
os.py389950644editdlrm
pathlib.py526100644editdlrm
pdb.py627380755editdlrm
pickle.py644670644editdlrm
pickletools.py934860644editdlrm
pipes.py89160644editdlrm
pkgutil.py214610644editdlrm
platform.py404250755editdlrm
plistlib.py324600644editdlrm
poplib.py152000644editdlrm
posixpath.py155000644editdlrm
pprint.py214840644editdlrm
profile.py235340755editdlrm
pstats.py273450644editdlrm
pty.py48070644editdlrm
pyclbr.py152550644editdlrm
pydoc.py1068630755editdlrm
py_compile.py81480644editdlrm
queue.py113560644editdlrm
quopri.py72520755editdlrm
random.py288020644editdlrm
re.py158610644editdlrm
reprlib.py52670644editdlrm
rlcompleter.py70970644editdlrm
runpy.py120520644editdlrm
sched.py64420644editdlrm
secrets.py20380644editdlrm
selectors.py185610644editdlrm
shelve.py85270644editdlrm
shlex.py133250644editdlrm
shutil.py514740644editdlrm
signal.py22730644editdlrm
site.py223360644editdlrm
sitecustomize.py-0editdlrm
smtpd.py347090755editdlrm
smtplib.py448040755editdlrm
sndhdr.py70990644editdlrm
socket.py352430644editdlrm
socketserver.py272960644editdlrm
sre_compile.py266950644editdlrm
sre_constants.py71540644editdlrm
sre_parse.py402300644editdlrm
ssl.py523630644editdlrm
stat.py54850644editdlrm
statistics.py396900644editdlrm
string.py105350644editdlrm
stringprep.py129170644editdlrm
struct.py2570644editdlrm
subprocess.py773300644editdlrm
sunau.py183750644editdlrm
symbol.py21090644editdlrm
symtable.py80210644editdlrm
sysconfig.py250350644editdlrm
tabnanny.py114060755editdlrm
tarfile.py955800755editdlrm
telnetlib.py232540644editdlrm
tempfile.py329200644editdlrm
textwrap.py194070644editdlrm
this.py10030644editdlrm
threading.py508200644editdlrm
timeit.py134800755editdlrm
token.py23680644editdlrm
tokenize.py258410644editdlrm
trace.py298580755editdlrm
traceback.py236110644editdlrm
tracemalloc.py170760644editdlrm
tty.py8790644editdlrm
turtle.py1437160644editdlrm
types.py97130644editdlrm
typing.py689620644editdlrm
uu.py69570755editdlrm
uuid.py304660644editdlrm
warnings.py196880644editdlrm
wave.py182300644editdlrm
weakref.py213870644editdlrm
webbrowser.py240830755editdlrm
xdrlib.py59130644editdlrm
zipapp.py75350644editdlrm
zipfile.py891350644editdlrm
zipimport.py307650644editdlrm
_bootlocale.py18010644editdlrm
_collections_abc.py261000644editdlrm
_compat_pickle.py87490644editdlrm
_compression.py53400644editdlrm
_dummy_thread.py60270644editdlrm
_markupbase.py145980644editdlrm
_osx_support.py217740644editdlrm
_pydecimal.py2286660644editdlrm
_pyio.py931770644editdlrm
_py_abc.py61890644editdlrm
_sitebuiltins.py31150644editdlrm
_strptime.py252680644editdlrm
_sysconfigdata__linux_x86_64-linux-gnu.py258340644editdlrm
_sysconfigdata__x86_64-linux-gnu.py258340644editdlrm
_threading_local.py72200644editdlrm
_weakrefset.py57350644editdlrm
__future__.py51470644editdlrm
__phello__.foo.py640644editdlrm
Edit: /snap/core20/2769/usr/lib/python3.8/timeit.py (13480B)
#! /usr/bin/python3.8 """Tool for measuring execution time of small code snippets. This module avoids a number of common traps for measuring execution times. See also Tim Peters' introduction to the Algorithms chapter in the Python Cookbook, published by O'Reilly. Library usage: see the Timer class. Command line usage: python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement] Options: -n/--number N: how many times to execute 'statement' (default: see below) -r/--repeat N: how many times to repeat the timer (default 5) -s/--setup S: statement to be executed once initially (default 'pass'). Execution time of this setup statement is NOT timed. -p/--process: use time.process_time() (default is time.perf_counter()) -v/--verbose: print raw timing results; repeat for more digits precision -u/--unit: set the output time unit (nsec, usec, msec, or sec) -h/--help: print this usage message and exit --: separate options from statement, use when statement starts with - statement: statement to be timed (default 'pass') A multi-line statement may be given by specifying each line as a separate argument; indented lines are possible by enclosing an argument in quotes and using leading spaces. Multiple -s options are treated similarly. If -n 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. Note: there is a certain baseline overhead associated with executing a pass statement. It differs between versions. 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. Classes: Timer Functions: timeit(string, string) -> float repeat(string, string) -> list default_timer() -> float """ import gc import sys import time import itertools __all__ = ["Timer", "timeit", "repeat", "default_timer"] dummy_src_name = "" default_number = 1000000 default_repeat = 5 default_timer = time.perf_counter _globals = globals # Don't change the indentation of the template; the reindent() calls # in Timer.__init__() depend on setup being indented 4 spaces and stmt # being indented 8 spaces. template = """ def inner(_it, _timer{init}): {setup} _t0 = _timer() for _i in _it: {stmt} _t1 = _timer() return _t1 - _t0 """ def reindent(src, indent): """Helper to reindent a multi-line statement.""" return src.replace("\n", "\n" + " "*indent) class Timer: """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' is specified, the code will be executed within that namespace (as opposed to inside timeit's namespace). To measure the execution time of the first statement, use the timeit() method. The repeat() method is a convenience to call timeit() multiple times and return a list of results. The statements may contain newlines, as long as they don't contain multi-line string literals. """ def __init__(self, stmt="pass", setup="pass", timer=default_timer, globals=None): """Constructor. See class doc string.""" self.timer = timer local_ns = {} global_ns = _globals() if globals is None else globals init = '' if isinstance(setup, str): # Check that the code can be compiled outside a function compile(setup, dummy_src_name, "exec") stmtprefix = setup + '\n' setup = reindent(setup, 4) elif callable(setup): local_ns['_setup'] = setup init += ', _setup=_setup' stmtprefix = '' setup = '_setup()' else: raise ValueError("setup is neither a string nor callable") if isinstance(stmt, str): # Check that the code can be compiled outside a function compile(stmtprefix + stmt, dummy_src_name, "exec") stmt = reindent(stmt, 8) elif callable(stmt): local_ns['_stmt'] = stmt init += ', _stmt=_stmt' stmt = '_stmt()' else: raise ValueError("stmt is neither a string nor callable") src = template.format(stmt=stmt, setup=setup, init=init) self.src = src # Save for traceback display code = compile(src, dummy_src_name, "exec") exec(code, global_ns, local_ns) self.inner = local_ns["inner"] def print_exc(self, file=None): """Helper to print a traceback from the timed code. Typical use: t = Timer(...) # outside the try/except try: t.timeit(...) # or t.repeat(...) except: t.print_exc() The advantage over the standard traceback is that source lines in the compiled template will be displayed. The optional file argument directs where the traceback is sent; it defaults to sys.stderr. """ import linecache, traceback if self.src is not None: linecache.cache[dummy_src_name] = (len(self.src), None, self.src.split("\n"), dummy_src_name) # else the source is already stored somewhere else traceback.print_exc(file=file) def timeit(self, number=default_number): """Time 'number' executions of the main statement. To be precise, this executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, as a float measured in seconds. 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. """ it = itertools.repeat(None, number) gcold = gc.isenabled() gc.disable() try: timing = self.inner(it, self.timer) finally: if gcold: gc.enable() return timing def repeat(self, repeat=default_repeat, number=default_number): """Call timeit() a few times. This is a convenience function that calls the timeit() repeatedly, returning a list of results. The first argument specifies how many times to call timeit(), defaulting to 5; the second argument specifies the timer argument, defaulting to one million. Note: 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 min() 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. """ r = [] for i in range(repeat): t = self.timeit(number) r.append(t) return r def autorange(self, callback=None): """Return the number of loops and time taken so that total time >= 0.2. Calls the timeit method with increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the time taken is at least 0.2 second. Returns (number, time_taken). If *callback* is given and is not None, it will be called after each trial with two arguments: ``callback(number, time_taken)``. """ i = 1 while True: for j in 1, 2, 5: number = i * j time_taken = self.timeit(number) if callback: callback(number, time_taken) if time_taken >= 0.2: return (number, time_taken) i *= 10 def timeit(stmt="pass", setup="pass", timer=default_timer, number=default_number, globals=None): """Convenience function to create Timer object and call timeit method.""" return Timer(stmt, setup, timer, globals).timeit(number) def repeat(stmt="pass", setup="pass", timer=default_timer, repeat=default_repeat, number=default_number, globals=None): """Convenience function to create Timer object and call repeat method.""" return Timer(stmt, setup, timer, globals).repeat(repeat, number) def main(args=None, *, _wrap_timer=None): """Main program, used when run as a script. The optional 'args' argument specifies the command line to be parsed, defaulting to sys.argv[1:]. The return value is an exit code to be passed to sys.exit(); it may be None to indicate success. When an exception happens during timing, a traceback is printed to stderr and the return value is 1. Exceptions at other times (including the template compilation) are not caught. '_wrap_timer' is an internal interface used for unit testing. If it is not None, it must be a callable that accepts a timer function and returns another timer function (used for unit testing). """ if args is None: args = sys.argv[1:] import getopt try: opts, args = getopt.getopt(args, "n:u:s:r:tcpvh", ["number=", "setup=", "repeat=", "time", "clock", "process", "verbose", "unit=", "help"]) except getopt.error as err: print(err) print("use -h/--help for command line help") return 2 timer = default_timer stmt = "\n".join(args) or "pass" number = 0 # auto-determine setup = [] repeat = default_repeat verbose = 0 time_unit = None units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0} precision = 3 for o, a in opts: if o in ("-n", "--number"): number = int(a) if o in ("-s", "--setup"): setup.append(a) if o in ("-u", "--unit"): if a in units: time_unit = a else: print("Unrecognized unit. Please select nsec, usec, msec, or sec.", file=sys.stderr) return 2 if o in ("-r", "--repeat"): repeat = int(a) if repeat <= 0: repeat = 1 if o in ("-p", "--process"): timer = time.process_time if o in ("-v", "--verbose"): if verbose: precision += 1 verbose += 1 if o in ("-h", "--help"): print(__doc__, end=' ') return 0 setup = "\n".join(setup) or "pass" # Include the current directory, so that local imports work (sys.path # contains the directory of this script, rather than the current # directory) import os sys.path.insert(0, os.curdir) if _wrap_timer is not None: timer = _wrap_timer(timer) t = Timer(stmt, setup, timer) if number == 0: # determine number so that 0.2 <= total time < 2.0 callback = None if verbose: def callback(number, time_taken): msg = "{num} loop{s} -> {secs:.{prec}g} secs" plural = (number != 1) print(msg.format(num=number, s='s' if plural else '', secs=time_taken, prec=precision)) try: number, _ = t.autorange(callback) except: t.print_exc() return 1 if verbose: print() try: raw_timings = t.repeat(repeat, number) except: t.print_exc() return 1 def format_time(dt): unit = time_unit if unit is not None: scale = units[unit] else: scales = [(scale, unit) for unit, scale in units.items()] scales.sort(reverse=True) for scale, unit in scales: if dt >= scale: break return "%.*g %s" % (precision, dt / scale, unit) if verbose: print("raw times: %s" % ", ".join(map(format_time, raw_timings))) print() timings = [dt / number for dt in raw_timings] best = min(timings) print("%d loop%s, best of %d: %s per loop" % (number, 's' if number != 1 else '', repeat, format_time(best))) best = min(timings) worst = max(timings) if worst >= best * 4: import warnings warnings.warn_explicit("The test results are likely unreliable. " "The worst time (%s) was more than four times " "slower than the best time (%s)." % (format_time(worst), format_time(best)), UserWarning, '', 0) return None if __name__ == "__main__": sys.exit(main())