timeit模块用于测试一段代码的执行效率

1.Timer类

Timer 类:

__init__(stmt="pass", setup="pass", timer=default_timer)

stmt 是执行语句,setup 是导入执行语句环境

print_exc(file=None)
timeit(number=default_number)

返回测试所用秒数,number 是每个测试中调用被计时语句的次数

repeat(repeat=default_repeat, number=default_number)

返回测试所用秒数列表,repeat 是重复整个测试的次数,number 是每个测试中执行语句的次数

快捷执行的方法:

timeit.timeit('time.time()','import time',number=10)
#这里会执行两次测试,每次测试都执行time.time()语句10次
timeit.repeat('time.time()','import time',repeat=2,number=10)

DEMO

import timeit
def f1():
for i in range(1000):
pass
def f2():
for i in xrange(1000):
pass
t=timeit.Timer('f1()','from __main__ import f1')
t1=timeit.Timer('f2()','from __main__ import f2')
print t.timeit()
print t1.timeit()

查看一个脚本的执行效率

python -m cProfile test_cprofile.py

2.测试Python不同用法的性能

代码:

#copy与deepcopy测试
print 'test copy and deepcopy'
import copy
x=range(1000)
print 'copy',timeit.timeit('copy.copy(x)','from __main__ import copy,x',number=100)
print 'deepcopy',timeit.timeit('copy.deepcopy(x)','from __main__ import copy,x',number=100)
#json和eval测试
import json
import ast
print 'test json and eval'
d=dict([(i,i) for i in xrange(1000)])
def test_json():
json.loads(json.dumps(d))
def test_ast():
ast.literal_eval(str(d))
print 'json',timeit.timeit('test_json()','from __main__ import test_json',number=100)
print 'ast',timeit.timeit('test_ast()','from __main__ import test_ast',number=100)
#while 1 和while True测试
print 'test while 1 and while True'
def while_one():
i=1000
while 1:
i-=1
if i<1:
break
def while_true():
i=1000
while True:
i-=1
if i<1:
break
print 'while 1',timeit.timeit('while_one()','from __main__ import while_one',number=1000)
print 'while true',timeit.timeit('while_true()','from __main__ import while_true',number=1000)
#测试map和列表解析
print 'map',timeit.timeit('map(lambda x:x+10,xrange(10000))',number=1000)
print 'list parse',timeit.timeit('[x+10 for x in xrange(10000)]',number=1000)
#测试filter和列表解析
print 'filter',timeit.timeit('filter(lambda x:x<5000,xrange(10000))',number=1000)
print 'list parse',timeit.timeit('[x for x in xrange(10000) if x<5000]',number=1000)
#测试zip和列表解析
d=[(i,i+1,i+2) for i in xrange(10000)]
print 'zip',timeit.timeit('zip(*d)[0]','from __main__ import d',number=1000)
print 'list parse',timeit.timeit('[x[0] for x in d]','from __main__ import d',number=1000)

测试结果:

test copy and deepcopy
copy 0.000615931092709
deepcopy 0.215742113851
test json and eval
json 0.0845840788228
ast 0.603505149528
test while 1 and while True
while 1 0.0920688664622
while true 0.107391902198
map 1.89678050601
list parse 0.741696814336
filter 1.42262613537
list parse 0.631220298896
zip 1.26682006617
list parse 0.993506476463

结论

  1. copy比deepcopy快
  2. json比ast快
  3. while 1比while True快
  4. 列表解析比map,filter,zip快

    5

    r1=[string[i:i+width] for i in xrange(0,len(string),width)]

    r2=re.findall(r".{%s}"%width,string)

    r1比r2快

参考博客

Python执行效率测试模块timei的使用方法与与常用Python用法的效率比较的更多相关文章

  1. Python 执行 javascript PyExecJS 模块

    PyExecJS 安装 pip install PyExecJS PyExecJS 的基本使用: >>> import execjs >>> execjs.eval ...

  2. 转载 jenkins执行selenium 测试 浏览器不显示解决方法

    原文地址: http://blog.csdn.net/achang21/article/details/45096003 The web browser doesn't show while run ...

  3. python:利用configparser模块读写配置文件

    在自动化测试过程中,为了提高脚本的可读性和降低维护成本,将一些通用信息写入配置文件,将重复使用的方法写成公共模块进行封装,使用时候直接调用即可. 这篇博客,介绍下python中利用configpars ...

  4. python里面的xlrd模块

    ♦python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库. 今天就先来说一下xlrd模块: 一.安装xlrd模块 ♦ 到python官网下载 ...

  5. python中日志logging模块的性能及多进程详解

    python中日志logging模块的性能及多进程详解 使用Python来写后台任务时,时常需要使用输出日志来记录程序运行的状态,并在发生错误时将错误的详细信息保存下来,以别调试和分析.Python的 ...

  6. python执行shell获取硬件参数写入mysql

    最近要获取服务器各种参数,包括cpu.内存.磁盘.型号等信息.试用了Hyperic HQ.Nagios和Snmp,它们功能都挺强大的,但是于需求不是太符,亦或者太heavy. 于是乎想到用python ...

  7. python里面的xlrd模块详解(一)

    那我就一下面积个问题对xlrd模块进行学习一下: 1.什么是xlrd模块? 2.为什么使用xlrd模块? 3.怎样使用xlrd模块? 1.什么是xlrd模块? python操作excel主要用到xlr ...

  8. python标准日志模块logging的使用方法

    参考地址 最近写一个爬虫系统,需要用到python的日志记录模块,于是便学习了一下.python的标准库里的日志系统从Python2.3开始支持.只要import logging这个模块即可使用.如果 ...

  9. Python 中 logging 日志模块在多进程环境下的使用

    因为我的个人网站 restran.net 已经启用,博客园的内容已经不再更新.请访问我的个人网站获取这篇文章的最新内容,Python 中 logging 日志模块在多进程环境下的使用 使用 Pytho ...

随机推荐

  1. css笔记19:浮动的案例

    案例一: 1. 首先是01.html文件: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &q ...

  2. javascript oop深入学习笔记(二)--javascript的函数

    一.概述: 函数是进行模块化程序设计的基础, javascript重的的函数不同于其他语言,每个函数都作为一个对象被维护和运行.通过函数对象的性质,可以很方便的将一个函数赋值给一个变量或则讲函数作为参 ...

  3. Objective-C ,ios,iphone开发基础:NSDictionary(字典) 和 NSMutableDictionary

    NSDictionary(字典),NSDictionary类似于 .net中的parameter,l类似于java中的map. 通过唯一的key找到对应的值,一个key只能对应一个只,而多个key可以 ...

  4. python 基础——*args和**kwargs

    *args表示任何多个无名参数,它是一个tuple:**kwargs表示关键字参数,它是一个dict. def func(one, *args, **kwargs): print type(one) ...

  5. oracle 10g升级到11g

    Linux 上Oracle RAC 10g 升级到 Oracle RAC 11g 了解如何在 Oracle Enterprise Linux 5 上逐步将 Oracle RAC 10g 第 2 版升级 ...

  6. LeetCode 122

    Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the price of a ...

  7. centos6.4搭建lnmp服务(转载)

    1.配置防火墙,开启80端口.3306端口vi /etc/sysconfig/iptables-A INPUT -m state --state NEW -m tcp -p tcp --dport 8 ...

  8. 转:基于Webrtc的跨平台实时语音通信解决方案(讲座)

    转:http://edu.csdn.net/course/detail/320/

  9. struts2-ajax-jQuery

    1.所需jar包如下所示.其中选中的四个包是struts2实现ajax所必需的,所有的jar包都可以从下载的完整的struts2 包中的lib文件夹中找到. 2.Demo struts2ajax.js ...

  10. JSP之request对象

    在请求转发时,我们需要把一些数据传递到转发后的页面进行处理.这时就需要使用request对象的setAttribute()方法将数据保存到request范围内的变量中. 示例:创建index.jsp文 ...