python timeit class Timer()类 timeit(string, string) repeat(string, string) default_timer() 耗时检测 执行速度
生活随笔
收集整理的這篇文章主要介紹了
python timeit class Timer()类 timeit(string, string) repeat(string, string) default_timer() 耗时检测 执行速度
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#! /usr/bin/env python3"""Tool for measuring execution time of small code snippets.
用于測量小代碼段執(zhí)行時間的工具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.該模塊避免了許多用于測量執(zhí)行時間的常見陷阱。
另請參閱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)多少次執(zhí)行“語句”(默認(rèn)值:請參見下文)-r/--repeat N: how many times to repeat the timer (default 3)重復(fù)多少次計時器(默認(rèn)3)-s/--setup S: statement to be executed once initially (default 'pass').Execution time of this setup statement is NOT timed.語句最初要執(zhí)行一次(默認(rèn)為“ pass”)。此安裝語句的執(zhí)行時間未計時。-p/--process: use time.process_time() (default is time.perf_counter())使用time.process_time()(默認(rèn)為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打印原始計時結(jié)果; 重復(fù)以提高數(shù)字精度-u/--unit: set the output time unit (usec, msec, or sec)設(shè)置輸出時間單位(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')要計時的語句(默認(rèn)為“通過”)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.
可以通過將每一行指定為單獨(dú)的參數(shù)來給出多行語句;
通過將引號括在引號中并使用前導(dǎo)空格,可以使行縮進(jìn)。 多個-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的連續(xù)冪直到總時間至少為0.2秒來計算合適的循環(huán)數(shù)。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.
注意:執(zhí)行pass語句有一定的基線開銷。 不同版本之間有所不同。
這里的代碼不會嘗試隱藏它,但是您應(yīng)該意識到這一點(diǎn)。 基線開銷可以通過不帶參數(shù)的程序來測量。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.
不要更改模板的縮進(jìn);
Timer .__ init __()中的reindent()調(diào)用取決于設(shè)置的縮進(jìn)4個空格和stmt縮進(jìn)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. 幫助程序重新縮進(jìn)多行語句"""return src.replace("\n", "\n" + " "*indent)class Timer:"""Class for timing execution speed of small code snippets.用于計時小代碼段的執(zhí)行速度的類。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).構(gòu)造函數(shù)接受一條要計時的語句,一條用于設(shè)置的附加語句以及一個計時器函數(shù)。 這兩個語句默認(rèn)為'pass'; 計時器功能取決于平臺(請參閱模塊文檔字符串)。 如果指定了'globals',則代碼將在該名稱空間內(nèi)執(zhí)行(與timetime內(nèi)部的名稱空間相對)。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.要測量第一條語句的執(zhí)行時間,請使用timeit()方法。 repeat()方法方便多次調(diào)用timeit()并返回結(jié)果列表。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# 檢查代碼是否可以在函數(shù)外部編譯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# 檢查代碼是否可以在函數(shù)外部編譯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.與標(biāo)準(zhǔn)回溯相比的優(yōu)勢在于,將顯示已編譯模板中的源代碼行。The optional file argument directs where the traceback issent; it defaults to sys.stderr.可選的文件參數(shù)指示回溯的發(fā)送位置。 它默認(rèn)為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.時間“數(shù)”主語句的執(zhí)行。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.確切地說,它只執(zhí)行一次setup語句,然后返回執(zhí)行主語句多次所需的時間,以秒為單位的浮點(diǎn)數(shù)。 參數(shù)是循環(huán)的次數(shù),默認(rèn)為一百萬次。 將要使用的主語句,設(shè)置語句和計時器函數(shù)傳遞給構(gòu)造函數(shù)。"""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. 多次調(diào)用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.這是一個便捷函數(shù),它反復(fù)調(diào)用timeit()并返回結(jié)果列表。 第一個參數(shù)指定調(diào)用timeit()的次數(shù),默認(rèn)為3。 第二個參數(shù)指定計時器參數(shù),默認(rèn)為一百萬。"""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.返回循環(huán)數(shù)和花費(fèi)的時間,以使總時間> = 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)``.調(diào)用timeit方法,并將* number *設(shè)置為連續(xù)的十次冪(10、100、1000 ...),最大為十億,直到花費(fèi)的時間至少為0.2秒,或者達(dá)到最大值。 返回``(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,它將在每次試用后使用兩個參數(shù)進(jìn)行調(diào)用:``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.方便的功能來創(chuàng)建Timer對象并調(diào)用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.方便的功能來創(chuàng)建Timer對象并調(diào)用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.主程序,作為腳本運(yùn)行時使用。The optional 'args' argument specifies the command line to be parsed,defaulting to sys.argv[1:].可選的“ args”參數(shù)指定要解析的命令行,默認(rèn)為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.當(dāng)計時期間發(fā)生異常時,會將追溯記錄輸出到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”是用于單元測試的內(nèi)部接口。 如果不是None,則它必須是可調(diào)用的,可以接受計時器函數(shù)并返回另一個計時器函數(shù)(用于單元測試)。"""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)# 包括當(dāng)前目錄,以便本地導(dǎo)入工作(sys.path包含此腳本的目錄,而不是當(dāng)前目錄)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())
總結(jié)
以上是生活随笔為你收集整理的python timeit class Timer()类 timeit(string, string) repeat(string, string) default_timer() 耗时检测 执行速度的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 计时器 timeit 报错
- 下一篇: python 计时器 timeit 报错