1. 简介

27.5. timeit — Measure execution time of small code snippets

Source code: Lib/timeit.py

timeit模块可以用来测试一段代码的执行耗时,如一个变量赋值语句的执行时间,一个函数的运行时间。

timeit是标准模块,无需安装。

import timeit

1.1. python interface

模块定义了三个方法和一个公共类。

1.1.1. timeit.timeit(stmt='pass', setup='pass', timer=, number=1000000, globals=None)

Create a Timer instance with the given statement, setup code and timer function and run its timeit() method with number executions. The optional globals argument specifies a namespace in which to execute the code.

参数说明:

  • stmt:测试代码,一般用函数(可以用字符串表达式)。
  • setup:传入stmt的运行环境,如参数,变量,模块。
  • timer:
  • number:执行次数,默认1000000
  • globals:

1.1.2. timeit.repeat(stmt='pass', setup='pass', timer=, repeat=3, number=1000000, globals=None)

Create a Timer instance with the given statement, setup code and timer function and run its repeat() method with the given repeat count and number executions. The optional globals argument specifies a namespace in which to execute the code.

参数说明:

  • repeat:重复次数,每次的结果构成列表返回,默认3次。

1.1.3. timeit.default_timer()

The default timer, which is always time.perf_counter().

Changed in version 3.3: time.perf_counter() is now the default timer.

1.1.4. class timeit.Timer(stmt='pass', setup='pass', timer=, globals=None)

Class for timing execution speed of small code snippets.

2. 案例

2.1. timeit() /repeat()

注意事项:

  1. 方法应在setup参数中导入;
  2. 变量需在setup参数中导入,且变量应为全局变量或直接传入;
  3. 测试次数number默认为10**6,注意修改,特别是单次执行时间较长时。
import timeit

def _test_timeit():
global a # timeit
a = [1,2,3,4]
t = timeit.timeit(stmt='_test_2(a)',
setup='from __main__ import _test_2, a',
number=100000)
print(t) # repeat
a = [1,2,3,4]
t = timeit.repeat(stmt='_test_2(a)',
setup='from __main__ import _test_2, a',
number=1000000,
repeat=5 )
print(t) def _test_2(s=None, *ar):
#s.insert(0, 45)
s.append(55) if __name__ == '__main__':
a = None
_test_timeit()
pass

输出:

0.02622983706364665
[0.28630844773090425, 0.2964419925588122, 0.23573263042489412, 0.2578145301438086, 0.22425034115163478]

说明:

repeat()与timeit()的区别在于它会重复测试多次,返回单次执行时间所组成的列表。

2.2. timer()

timer()实质是timeit()和repeat()的底层实现;

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)

也可以使用Timer()初始化然后调用其方法timeit和repeat。

python lib timeit 测试运行时间的更多相关文章

  1. C#测试运行时间

    System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); //开始监视代码运行时间 ...

  2. python解无忧公主的数学时间编程题001.py

    python解无忧公主的数学时间编程题001.py """ python解无忧公主的数学时间编程题001.py http://mp.weixin.qq.com/s?__b ...

  3. python解无忧公主的数学时间097.py

    python解无忧公主的数学时间097.py """ python解无忧公主的数学时间097.py codegay 2016年3月30日 00:17:26 http:// ...

  4. Python实现进度条和时间预估的示例代码

    一.前言 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知识.那么针对这三类人,我给大家 ...

  5. python设置socket的超时时间(可能使用locust压测千级并发的时候要用到,先记录在此)

    在使用urllib或者urllib2时,有可能会等半天资源都下载不下来,可以通过设置socket的超时时间,来控制下载内容时的等待时间. 如下python代码 import socket timeou ...

  6. python之timeit模块

    timeit模块: timeit 模块定义了接受两个参数的 Timer 类.两个参数都是字符串. 第一个参数是你要计时的语句或者函数. 传递给 Timer 的第二个参数是为第一个参数语句构建环境的导入 ...

  7. python常用标准库(时间模块 time和datetime)

    常用的标准库 time时间模块 import time time -- 获取本地时间戳 时间戳又被称之为是Unix时间戳,原本是在Unix系统中的计时工具. 它的含义是从1970年1月1日(UTC/G ...

  8. Python学习总结15:时间模块datetime & time & calendar (二)

    二 .datetime模块  1. datetime中常量 1)datetime.MINYEAR,表示datetime所能表示的最小年份,MINYEAR = 1. 2)datetime.MAXYEAR ...

  9. Python学习总结14:时间模块datetime & time & calendar (一)

    Python中的常用于处理时间主要有3个模块datetime模块.time模块和calendar模块. 一.time模块 1. 在Python中表示时间的方式 1)时间戳(timestamp):通常来 ...

随机推荐

  1. Python基础笔记2

    @time 2019/12/17 12:04 一.列表 1.增加数据:append.insert方法 names = ["兰陵王", "孙悟空", " ...

  2. pom中<scope></scope>一些理解

    compile:默认值,表示当前依赖包,要参与当前项目的编译,后续测试,运行时,打包provided:代表在编译和测试的时候用,运行,打包的时候不会打包进去test:表示当前依赖包只参与测试时的工作: ...

  3. 机器学习作业(五)机器学习算法的选择与优化——Matlab实现

    题目下载[传送门] 第1步:读取数据文件,并可视化: % Load from ex5data1: % You will have X, y, Xval, yval, Xtest, ytest in y ...

  4. Spring boot unable to determine jdbc url from datasouce

    1. 首先删除 @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) 2. 在配置文件里添加完整的dataso ...

  5. 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。”

    出现场景: From1中事件B绑定在事件A,事件A由工厂模式下的设备产生,当离开Form1时,设备中的事件A仍然会触发事件B,此时就会导致如上问题 原因(个人理解): 1.Form1已经被销毁了,但仍 ...

  6. update(十)

    Vue 的 _update 是实例的一个私有方法,它被调用的时机有 2 个,一个是首次渲染,一个是数据更新的时候:由于我们这一章节只分析首次渲染部分,数据更新部分会在之后分析响应式原理的时候涉及._u ...

  7. java 学习(day2) 时钟类

    看过python的面向对象,所以入手java总的来说还是比较快的. 看视频学习之后写了一个简单的时钟 一个时钟有两部分组成小时和分钟.再大一些还有月,日. 分析一下就是,上述这些属性到达一个值之后,就 ...

  8. hibernate跟Mybatis/ ibatis 的区别,为什么选择?(转)

    第一章 Hibernate与MyBatisHibernate 是当前最流行的O/R mapping框架,它出身于sf.NET,现在已经成为Jboss的一部分. Mybatis 是另外一种优秀的O/R ...

  9. K8s控制器

    K8s控制器 POD分类 #自主式pod:退出后,不会被创建 #控制器管理的pod:在控制器的生命周期内,始终位置pod的副本数 控制器类型 ReplicationController和Replica ...

  10. 《深入理解Java虚拟机》读书笔记三

    第四章 虚拟机性能监控与故障处理工具 1.JDK命令行工具 jps命令: 作用:列出正在运行的虚拟机进程. 格式:jps [option] [hostid] 选项:-q 只输出LVMID(Local ...