Python内置类型性能分析
来源:互联网 发布:ubuntu 播放器推荐 编辑:程序博客网 时间:2024/05/18 02:10
Python内置类型性能分析
timeit模块
timeit模块可以用来测试一小段Python代码的执行速度。
class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)
Timer是测量小段代码执行速度的类。
stmt参数是要测试的代码语句(statment);
setup参数是运行代码时需要的设置;
timer参数是一个定时器函数,与平台有关。
timeit.Timer.timeit(number=1000000):测试代码执行num次的平均时间
Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次。方法返回执行代码的平均耗时,一个float类型的秒数。
list的操作测试
def test1():
l = [] for i in range(1000): l = l + [i]def test2(): l = [] for i in range(1000): l.append(i)def test3(): l = [i for i in range(1000)]def test4(): l = list(range(1000))from timeit import Timert1 = Timer("test1()", "from __main__ import test1") #通常测试不在当前文件,需要导入对应的py文件print("concat ",t1.timeit(number=1000), "seconds")t2 = Timer("test2()", "from __main__ import test2")print("append ",t2.timeit(number=1000), "seconds")t3 = Timer("test3()", "from __main__ import test3")print("comprehension ",t3.timeit(number=1000), "seconds")t4 = Timer("test4()", "from __main__ import test4")print("list range ",t4.timeit(number=1000), "seconds")# ('concat ', 1.7890608310699463, 'seconds')# ('append ', 0.13796091079711914, 'seconds')# ('comprehension ', 0.05671119689941406, 'seconds')# ('list range ', 0.014147043228149414, 'seconds')
pop操作测试
x = range(2000000)pop_zero = Timer("x.pop(0)","from __main__ import x")print("pop_zero ",pop_zero.timeit(number=1000), "seconds")x = range(2000000)pop_end = Timer("x.pop()","from __main__ import x")print("pop_end ",pop_end.timeit(number=1000), "seconds")# ('pop_zero ', 1.9101738929748535, 'seconds')# ('pop_end ', 0.00023603439331054688, 'seconds')
测试pop操作:从结果可以看出,pop最后一个元素的效率远远高于pop第一个元素
list内置操作的时间复杂度
dict内置操作的时间复杂度
阅读全文
0 0
- Python内置类型性能分析
- Python内置类型性能分析--list
- python内置类型
- python内置对象类型
- Python扩展内置类型
- Python 内置类型简述
- python内置类型
- Python的基本内置类型
- Python的基本内置类型
- Python入门:内置基础类型
- Python内置类型转换函数
- Python的内置类型续
- python中的内置基本类型
- Python 入门 - Python 的内置数值类型
- Python速查笔记(2) 内置类型
- python内置类型(list,dictionary, tuple , string, )
- Python的数据类型(内置类型)
- python内置类型(未完待续)
- Pointers on C——9 Strings, Characters, and Bytes.6
- 回音消除技术概述
- Mybatis + SqlServer 数据库操作insert 时获取当前主键值
- dom4j(XML解析)私人学习笔记
- Pointers on C——9 Strings, Characters, and Bytes.7
- Python内置类型性能分析
- redis config的配置
- js解析当前页面url获取参数
- Pointers on C——9 Strings, Characters, and Bytes.8
- 逆转?不会
- test
- David Silver《Reinforcement Learning》课程解读—— Lecture 5: Model-Free Control
- Pointers on C——9 Strings, Characters, and Bytes.9
- 正则表达式