#! /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() 耗时检测 执行速度相关推荐

  1. Python中计算程序的运行时间——timeit模块

    Python中计算程序的运行时间--timeit模块 绪论 一.timeit的基本用法 1.1 timeit.timeit()函数: 创建一个Timer实例,并运行代码进行计时,默认将代码执行一百万次 ...

  2. timeit.Timer()与timeit.timeit()

    1.使用场景: timeit 模块用于测量代码片段的执行时间 2.使用方式: 1)使用 shell 或 dos 的命令行界面,如下: python -m timeit [-n N] [-r N] [- ...

  3. Python数据结构与算法(二)--timeit模块

    Python内置性能分析,timeit模块 timeit模块可以用来测试一小段Python代码的执行速度. class timeit.Timer(stmt='pass', setup='pass', ...

  4. python string模块安装_python String模块-阿里云开发者社区

    string成员常量: ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHI JKLMNOPQRSTUVWXYZ' ascii_lowercase  ...

  5. Python学习笔记:利用timeit计算函数调用耗时

    Python学习笔记:利用timeit计算函数调用耗时 一.timeit模块简介 Timer对象包含两个参数:第一个参数是你想要计时的Python语句,第二个参数运行一次来建立测试. 默认情况time ...

  6. java中String类是什么_Java中的String类

    /* String类用于描述字符串事物的 那么它就提供了多个方法对字符串进行操作 方法都会用,字符串这块就结束了 常见的操作有哪些? "abcd" 它应该具备什么功能,我们才能更好 ...

  7. C++string类常用函数 c++中的string常用函数用法总结

    string类的构造函数: string(const char *s);    //用c字符串s初始化 string(int n,char c);     //用n个字符c初始化 此外,string类 ...

  8. Java中String类的concat方法___java的String字符串的concat()方法连接字符串和“+“连接字符串解释

    Java中String类的concat方法 在了解concat()之前,首先需要明确的是String的两点特殊性. 长度不可变 值不可变 这两点从源码中对String的声明可以体现: private ...

  9. 【STL】string详解(string类常用的操作函数、构造函数、赋值操作、子符串的拼接、查找和替换、比较、存取、插入和删除、获取)

    目录 1. string容器 简介 2. string类常用的操作函数 3. 构造函数 4. 赋值操作 5. 字符串拼接 6. 字符串查找和替换 7. 字符串比较 8. 字符串存取 9. 字符串插入和 ...

最新文章

  1. Matlab与线性代数 -- 矩阵的重组4
  2. Spring Security 实战:Spring Boot 下的自动配置
  3. Java中恒等条件判断:“equals”和“==”
  4. indesign如何画弧线_【美妆】鼻影怎么画,才能拥有比例完美的鼻子?
  5. python虚拟人脸生成_Python-OpenCV人脸识别之数据集生成
  6. MySQL快速上手[学习笔记](二)
  7. Continue(Java)
  8. 【安装包】android-studio
  9. JAVA毕设项目图书馆预约占座系统(java+VUE+Mybatis+Maven+Mysql)
  10. java 自定义进度条_JAVA Swing 自定义进度条样式(简单实现)
  11. db,dbm,w,dbw,mw的换算关系
  12. 不知道PDF转Word用什么软件?试试这3款实用软件
  13. 苹果4怎么越狱_它的维生素C含量是苹果的4倍,是我国第4大主粮,土豆怎么种植的...
  14. 目标检测YOLO实战应用案例100讲-基于深度学习的显著性目标检测研究与应用(论文篇)
  15. SylixOS中APIC HPET定时器字符驱动实现
  16. 即时通讯视频聊天代码和技术架构
  17. 推荐系统笔记(MAB问题)
  18. Java开发谈:java如何开发安卓软件
  19. JAVA图形界面设计
  20. 2017南京师范大学计算机学院录取名单,关于公布南京师范大学2017年硕士研究生复试成绩及录取名单的通知...

热门文章

  1. REM重复制造的冲销
  2. SAP请求传输事务代码
  3. SAP创建生产订单时要求输入销售订单
  4. 递归方法计划销售订单的计划物料成本
  5. Swift vs. Objective-C:未来看好Swift的十个理由
  6. 利用BADI ME_PROCESS_PO_CUST進行PO check
  7. SAP同一公司不同工厂间物料转储方案比较
  8. CONVERT_DATE_INPUT
  9. 青瓷游戏上市首日破发,“元宇宙光环”能否拯救年内首支游戏股?
  10. c++编写算法判断二叉树是否为完全二叉树_[校招-算法题] 二叉树基础算法1