欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

python timeit class Timer()类 timeit(string, string) repeat(string, string) default_timer() 耗时检测 执行速度

发布时间:2025/3/20 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python timeit class Timer()类 timeit(string, string) repeat(string, string) default_timer() 耗时检测 执行速度 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
#! /usr/bin/env python3"""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.该模块避免了许多用于测量执行时间的常见陷阱。 另请参阅O'Reilly出版的Python Cookbook中Tim Peters对算法一章的介绍。Library usage: see the Timer class.Command line usage:python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-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 3)重复多少次计时器(默认3)-s/--setup S: statement to be executed once initially (default 'pass').Execution time of this setup statement is NOT timed.语句最初要执行一次(默认为“ pass”)。此安装语句的执行时间未计时。-p/--process: use time.process_time() (default is time.perf_counter())使用time.process_time()(默认为time.perf_counter())-t/--time: use time.time() (deprecated)使用time.time()(不建议使用)-c/--clock: use time.clock() (deprecated)使用time.clock()(不建议使用)-v/--verbose: print raw timing results; repeat for more digits precision打印原始计时结果; 重复以提高数字精度-u/--unit: set the output time unit (usec, msec, or sec)设置输出时间单位(usec,msec或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. 可以通过将每一行指定为单独的参数来给出多行语句; 通过将引号括在引号中并使用前导空格,可以使行缩进。 多个-s选项的处理方式类似。If -n is not given, a suitable number of loops is calculated by trying successive powers of 10 until the total time is at least 0.2 seconds. 如果未给出-n,则通过尝试10的连续幂直到总时间至少为0.2秒来计算合适的循环数。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. 注意:执行pass语句有一定的基线开销。 不同版本之间有所不同。 这里的代码不会尝试隐藏它,但是您应该意识到这一点。 基线开销可以通过不带参数的程序来测量。Classes:TimerFunctions:timeit(string, string) -> floatrepeat(string, string) -> listdefault_timer() -> float"""import gc import sys import time import itertools__all__ = ["Timer", "timeit", "repeat", "default_timer"]dummy_src_name = "<timeit-src>" default_number = 1000000 default_repeat = 3 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. 不要更改模板的缩进; Timer .__ init __()中的reindent()调用取决于设置的缩进4个空格和stmt缩进8个空格。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 additionalstatement used for setup, and a timer function. Both statementsdefault to 'pass'; the timer function is platform-dependent (seemodule doc string). If 'globals' is specified, the code will beexecuted within that namespace (as opposed to inside timeit'snamespace).构造函数接受一条要计时的语句,一条用于设置的附加语句以及一个计时器函数。 这两个语句默认为'pass'; 计时器功能取决于平台(请参阅模块文档字符串)。 如果指定了'globals',则代码将在该名称空间内执行(与timetime内部的名称空间相对)。To measure the execution time of the first statement, use thetimeit() method. The repeat() method is a convenience to calltimeit() multiple times and return a list of results.要测量第一条语句的执行时间,请使用timeit()方法。 repeat()方法方便多次调用timeit()并返回结果列表。The statements may contain newlines, as long as they don't containmulti-line string literals.语句可以包含换行符,只要它们不包含多行字符串文字即可。"""def __init__(self, stmt="pass", setup="pass", timer=default_timer,globals=None):"""Constructor. See class doc string."""self.timer = timerlocal_ns = {}global_ns = _globals() if globals is None else globalsinit = ''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'] = setupinit += ', _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'] = stmtinit += ', _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 displaycode = 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/excepttry:t.timeit(...) # or t.repeat(...)except:t.print_exc()The advantage over the standard traceback is that source linesin the compiled template will be displayed.与标准回溯相比的优势在于,将显示已编译模板中的源代码行。The optional file argument directs where the traceback issent; it defaults to sys.stderr.可选的文件参数指示回溯的发送位置。 它默认为sys.stderr。"""import linecache, tracebackif 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 elsetraceback.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, andthen returns the time it takes to execute the main statementa number of times, as a float measured in seconds. Theargument is the number of times through the loop, defaultingto one million. The main statement, the setup statement andthe timer function to be used are passed to the constructor.确切地说,它只执行一次setup语句,然后返回执行主语句多次所需的时间,以秒为单位的浮点数。 参数是循环的次数,默认为一百万次。 将要使用的主语句,设置语句和计时器函数传递给构造函数。"""it = itertools.repeat(None, number)gcold = gc.isenabled()gc.disable()try:timing = self.inner(it, self.timer)finally:if gcold:gc.enable()return timingdef repeat(self, repeat=default_repeat, number=default_number):"""Call timeit() a few times. 多次调用timeit()。This is a convenience function that calls the timeit()repeatedly, returning a list of results. The first argumentspecifies how many times to call timeit(), defaulting to 3;the second argument specifies the timer argument, defaultingto one million.Note: it's tempting to calculate mean and standard deviationfrom the result vector and report these. However, this is notvery useful. In a typical case, the lowest value gives alower bound for how fast your machine can run the given codesnippet; higher values in the result vector are typically notcaused by variability in Python's speed, but by otherprocesses interfering with your timing accuracy. So the min()of the result is probably the only number you should beinterested in. After that, you should look at the entirevector and apply common sense rather than statistics.这是一个便捷函数,它反复调用timeit()并返回结果列表。 第一个参数指定调用timeit()的次数,默认为3。 第二个参数指定计时器参数,默认为一百万。"""r = []for i in range(repeat):t = self.timeit(number)r.append(t)return rdef autorange(self, callback=None):"""Return the number of loops and time taken so that total time >= 0.2.返回循环数和花费的时间,以使总时间> = 0.2。Calls the timeit method with *number* set to successive powers often (10, 100, 1000, ...) up to a maximum of one billion, untilthe time taken is at least 0.2 second, or the maximum is reached.Returns ``(number, time_taken)``.调用timeit方法,并将* number *设置为连续的十次幂(10、100、1000 ...),最大为十亿,直到花费的时间至少为0.2秒,或者达到最大值。 返回``(number,time_taken)``。If *callback* is given and is not None, it will be called aftereach trial with two arguments: ``callback(number, time_taken)``.如果给定* callback *且不为None,它将在每次试用后使用两个参数进行调用:``callback(number,time_taken)``。"""for i in range(1, 10):number = 10**itime_taken = self.timeit(number)if callback:callback(number, time_taken)if time_taken >= 0.2:breakreturn (number, time_taken)def timeit(stmt="pass", setup="pass", timer=default_timer,number=default_number, globals=None):"""Convenience function to create Timer object and call timeit method.方便的功能来创建Timer对象并调用timeit方法。"""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.方便的功能来创建Timer对象并调用repeat方法。"""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:].可选的“ args”参数指定要解析的命令行,默认为sys.argv [1:]。The return value is an exit code to be passed to sys.exit(); itmay be None to indicate success.返回值是要传递给sys.exit()的退出代码; 表示没有可能表示成功。When an exception happens during timing, a traceback is printed tostderr and the return value is 1. Exceptions at other times(including the template compilation) are not caught.当计时期间发生异常时,会将追溯记录输出到stderr,并且返回值为1。不会捕获其他时间(包括模板编译)的异常。'_wrap_timer' is an internal interface used for unit testing. If itis not None, it must be a callable that accepts a timer functionand returns another timer function (used for unit testing).“ _wrap_timer”是用于单元测试的内部接口。 如果不是None,则它必须是可调用的,可以接受计时器函数并返回另一个计时器函数(用于单元测试)。"""if args is None:args = sys.argv[1:]import getopttry: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 2timer = default_timerstmt = "\n".join(args) or "pass"number = 0 # auto-determinesetup = []repeat = default_repeatverbose = 0time_unit = Noneunits = {"usec": 1, "msec": 1e3, "sec": 1e6}precision = 3for 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 = aelse:print("Unrecognized unit. Please select usec, msec, or sec.",file=sys.stderr)return 2if o in ("-r", "--repeat"):repeat = int(a)if repeat <= 0:repeat = 1if o in ("-t", "--time"):timer = time.timeif o in ("-c", "--clock"):timer = time.clockif o in ("-p", "--process"):timer = time.process_timeif o in ("-v", "--verbose"):if verbose:precision += 1verbose += 1if o in ("-h", "--help"):print(__doc__, end=' ')return 0setup = "\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)# 包括当前目录,以便本地导入工作(sys.path包含此脚本的目录,而不是当前目录)import ossys.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.0callback = Noneif verbose:def callback(number, time_taken):msg = "{num} loops -> {secs:.{prec}g} secs"print(msg.format(num=number, secs=time_taken, prec=precision))try:number, _ = t.autorange(callback)except:t.print_exc()return 1try:r = t.repeat(repeat, number)except:t.print_exc()return 1best = min(r)if verbose:print("raw times:", " ".join(["%.*g" % (precision, x) for x in r]))print("%d loops," % number, end=' ')usec = best * 1e6 / numberif time_unit is not None:scale = units[time_unit]else:scales = [(scale, unit) for unit, scale in units.items()]scales.sort(reverse=True)for scale, time_unit in scales:if usec >= scale:breakprint("best of %d: %.*g %s per loop" % (repeat, precision,usec/scale, time_unit))best = min(r)usec = best * 1e6 / numberworst = max(r)if worst >= best * 4:usec = worst * 1e6 / numberimport warningswarnings.warn_explicit("The test results are likely unreliable. The worst\n""time (%.*g %s) was more than four times slower than the best time." %(precision, usec/scale, time_unit),UserWarning, '', 0)return Noneif __name__ == "__main__":sys.exit(main())

总结

以上是生活随笔为你收集整理的python timeit class Timer()类 timeit(string, string) repeat(string, string) default_timer() 耗时检测 执行速度的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。