Python3中的timeit模块可以用来测试小段代码的运行时间

其中主要通过两个函数来实现: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)

在上面的代码中可见,无论是timeit还是repeat都是先生成Timer对象,然后调用了Timer对象的timeit或repeat函数。

在使用timeit模块时,可以直接使用timeit.timeit()、tiemit.repeat(),还可以先用timeit.Timer()来生成一个Timer对象,然后再用TImer对象用timeit()和repeat()函数,后者再灵活一些。

上述两个函数的入参:

stmt:用于传入要测试时间的代码,可以直接接受字符串的表达式,也可以接受单个变量,也可以接受函数。传入函数时要把函数申明在当前文件中,然后在 stmt = ‘func()’ 执行函数,然后使用 setup = ‘from __main__ import func’

setup:传入stmt的运行环境,比如stmt中使用到的参数、变量,要导入的模块等。可以写一行语句,也可以写多行语句,写多行语句时要用分号;隔开语句。

number:要测试的代码的运行次数,默认100000次,对于耗时的代码,运行太多次会比较慢,此时建议自己修改一下运行次数

repeat:指测试要重复几次,每次的结果构成列表返回,默认3次。

一、直接使用timeit.timeit()、tiemit.repeat():

import timeit 

print(timeit.timeit(stmt= 'list(i**2 for i in normal_list)',setup = 'normal_list=range(10000)',number=10))
#0.3437936799875755
print(timeit.repeat(stmt= 'list(i**2 for i in normal_list)', setup='normal_list=range(10000)',repeat=2,number=10))
#[0.33649995761778984, 0.3394490767789293]
#setup 为复合语句
print(timeit.timeit(stmt= 'list(i**2 for i in normal_list)',setup = 'a=10000;normal_list=range(a)',number=10))
#0.33272367424748817
print(timeit.repeat(stmt= 'list(i**2 for i in normal_list)', setup='a=10000;normal_list=range(a)',repeat=2,number=10))
#[0.3323106610316342, 0.3356380911962764] def func():
normal_list=range(10000)
L = [i**2 for i in normal_list] #stmt为函数
print(timeit.timeit("func()", setup="from __main__ import func",number=10))
#0.12436874684622312
print(timeit.repeat("func()", setup="from __main__ import func",repeat=2,number=10))
#[0.12142133435126468, 0.12079555675148601]

直接用函数的方式,速度更快。

二、先生成Timer,再调用timeit()、repeat():

import timeit 

#生成timer
timer1 = timeit.Timer(stmt= 'list(i**2 for i in normal_list)',setup = 'normal_list=range(10000)')
#调用timeit和repeat时还传number和repeat参数
print(timer1.timeit(number=10))
#0.34721554568091145
print(timer1.repeat(repeat=2,number=10))
#[0.3391925079630199, 0.34103400077255097] #setup 为复合语句
timer1 = timeit.Timer(stmt= 'list(i**2 for i in normal_list)',setup = 'a=10000;normal_list=range(a)')
print(timer1.timeit(number=10))
0.34383463997592467
print(timer1.repeat(repeat=2,number=10))
#[0.34573984832288773, 0.34413273766891006] #stmt为函数
def func():
normal_list=range(10000)
L = [i**2 for i in normal_list] timer1 = timeit.Timer("func()", setup="from __main__ import func")
print(timer1.timeit(number=10))
#0.1223264363160359
print(timer1.repeat(repeat=2,number=10))
#[0.12266321844246209, 0.1264150395975001]

Python3 timeit的用法的更多相关文章

  1. python3 字典常见用法总结

    python3 字典常见用法总结 Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串.数字.元组等其他容器模型. 一.创建字典 字典由键和对应值成对组成.字典也被称作关联数组或哈希表 ...

  2. Python3 range() 函数用法

    Python3 range() 函数用法  Python3 内置函数 Python3 range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表. Pyth ...

  3. python timeit模块用法

    想测试一行代码的运行时间,在python中比较方便,可以直接使用timeit: >>> import timeit #执行命令 >>> t2 = timeit.Ti ...

  4. Python3基础-高级用法

    写在前面:本文主要是python高级练习部分,介绍了一些高级用法,这些都是零散的小知识,这些可以与函数式编程合在一起使用. 函数式编程1:Python中提供的函数式编程主要有: map(函数,可迭代式 ...

  5. python3 numpy基本用法归纳总结

    安装numpy : pip install numpy numpy数组生成方法总结 In [4]: import numpy as np #使用列表生成一个一维数组 data = [1,2,3,4,5 ...

  6. Python3 pickle模块用法

    pickle(python3.x)和cPickle(python2.x的模块)相当于java的序列化和反序列化操作. 常采用下面的方式使用: import pickle pickle.dump(obj ...

  7. python3装饰器用法示例

    装饰器在编写后台的逻辑时有可能会用到,比方说一个场景:公司的员工想要登录自己公司的考勤记录系统去修改自己的考勤,以前是随便谁都有权限去修改,这样老板不同意了,现在,要在你登录前加一个权限验证的逻辑,如 ...

  8. python3正则表达式详细用法示例

    转载自:https://www.runoob.com/python3/python3-reg-expressions.html

  9. python2到python3的转换以及f.write在python3 中的用法

    .利用Python内置(Python脚本)工具,帮你自动转换 Python 2.x版本,比如我安装的Python 2.7.2,其在windows下载安装好之后,就自带了相关的一些有用的工具. 其中一个 ...

随机推荐

  1. 剑指Offer 27. 字符串的排列 (字符串)

    题目描述 输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba. 输入描述: 输 ...

  2. linux子系统搭建python3

    我之前win10系统有py3,所以就没有下载,直接输入python ,就会进入python环境,但是,什么包都没有 安装pip $ wget https://bootstrap.pypa.io/get ...

  3. Python开发 基礎知識 3.類別&方法 (bool & str) (未完待續)

    類別 可使用type()查看 內建 [ 布爾:bool (Boolen) 字串:str (String) 數字:int (Integer) 小數:float 列表:list 元祖:tuple 字典:d ...

  4. WRITING POSTGRESQL TRIGGERS IN GO

    转自:https://www.opsdash.com/blog/postgresql-triggers-golang.html 可以学习如何使用golang 编写pg extension Trigge ...

  5. java 从一个工程action 跳转到另外一个工程action

    实现功能:java 从一个工程action 跳转到另外一个工程action 在我们实际编程的过程中,大家一定遇到过这种情况,那就是在一个工程中,需要使用到另外一个工程的实体Bean和方法.那么遇到这种 ...

  6. Python中*args和**kwargs

    *args *args是可变的positional arguments列表 *args:将参数打包成元组(tuple)给函数调用 在函数中用 args 调用 **kwargs **kwargs是可变的 ...

  7. because there was insufficient free space available after evicting expired cache entries

    Tomcat运行的时候哗哗哗的报警告 版本是Tomcat 8.5.15 告警信息关键字如下 because there was insufficient free space available af ...

  8. PLC 通讯

    几个之前整理的高级语言与PLC通讯的资源下载链接:三菱:http://blog.sina.com.cn/s/blog_16d7d3ecb0102x6wj.html倍福:http://bbs.elecf ...

  9. Linux初级入门(第一次作业)

    Linux初级入门 在本科期间学过一些Linux的简单命令,再次接触Linux不仅巩固了知识还学习到了很多新的东西. 什么是操作系统? 操作系统,英文名称Operating System,简称OS,是 ...

  10. javaScript 中的私有,共有,特权属性和方法

    function constructor () { var private_v; // 私有属性 var private_f = function () { // 私有方法 // code }; th ...