日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/20 python 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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() 耗时检测 执行速度的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 成人精品影院 | 国内激情 | 久久久久麻豆v国产精华液好用吗 | 三级网站在线播放 | 色啪综合 | 国产三区视频 | 国产午夜一级一片免费播放 | 国产成人在线影院 | а√中文在线资源库 | 国产成人在线视频网站 | 精品久久无码视频 | 天天躁日日躁狠狠躁av麻豆男男 | 日本在线黄色 | 国产精品后入内射日本在线观看 | 欧美日韩一级黄色片 | 少妇把腿扒开让我舔18 | 日韩欧美偷拍 | av不卡一区二区 | 五月婷婷,六月丁香 | 男人的av| 一本加勒比北条麻妃 | 色欲久久久天天天综合网精品 | 欧洲中文字幕日韩精品成人 | 国产精选一区二区 | 六月激情婷婷 | 男人用嘴添女人下身免费视频 | 亚洲色图视频网站 | 第一区免费在线观看 | 中文字幕第一页av | 男女插插视频 | 打开免费观看视频在线播放 | 99产精品成人啪免费网站 | 成年人在线视频观看 | 综合精品在线 | 日韩精品视频一区二区在线观看 | 在线免费观看的av | 亚洲精品一区二区三区不卡 | 在线欧美国产 | 一区二区三区在线播放视频 | 91超碰免费 | 久久av一区二区 | 欧美一区在线观看视频 | 久久国产热 | 久久久久久久久蜜桃 | 欧美一级淫片免费视频黄 | 波多野结衣办公室33分钟 | 国产偷亚洲偷欧美偷精品 | 少妇一级淫片日本 | 69色综合 | 天天综合影院 | 曰韩毛片 | 午夜国产片 | 成年人黄色免费网站 | 制服丝袜一区 | www.国产91 | 国产理论影院 | 国产一区二区三区91 | 新香蕉视频 | 男女啪啪在线观看 | 国产色在线观看 | 男女激情大尺度做爰视频 | 中文字幕免费高清视频 | 青青自拍视频 | 狠狠操狠狠插 | 美女av免费观看 | 亚洲精品在线播放视频 | 国产一区二区啪啪啪 | 日韩欧美一二三四区 | 欧日韩不卡视频 | 影音先锋中文字幕人妻 | 五月婷婷综合激情网 | 一级色视频| 91插插视频 | 国产电影一区二区三区爱妃记 | 欧美日韩成人在线视频 | 黄色av网| 免费三片在线观看网站v888 | 日韩亚洲欧美在线观看 | 妻子的性幻想 | 欧美香蕉在线 | 成人深夜福利视频 | 韩国毛片一区二区三区 | av片子在线观看 | 加勒比伊人 | 日本一本在线 | 2021av| 日本不卡二区 | 国产裸体永久免费无遮挡 | 久草av在线播放 | 久热网| 日本乱子伦xxxx | 凹凸日日摸日日碰夜夜 | 国产黄色在线免费观看 | 九九久久国产精品 | 日韩一区二区三区四区五区六区 | 色综合av综合无码综合网站 | 国产第七页 | 91精彩刺激对白 | 国产三级播放 |