在写MATLAB的脚本的时候我时长会用tic、toc进行一下程序运行时间的测量。在Python中偶尔也会测试下,但是基本上都是靠使用time模块。接触了IPython之后突然间发现,原来程序执行时间的测试可以如此简单!
在IPython中,程序执行时间的测试是通过魔术函数来实现。这个功能的魔术函数有两个,一个是time,还有一个是timeit。后面这个功能与前面的功能类似,但是更为精确,因为测试采用了多次测试求取平均值的方式实现。
之前写了一个简单的测试小脚本,
#!/usr/bin/python import numpy as npfrom numpy.randomimport randn data = {i :randn() for i in range(7)}
print(data)代码如下:
在IPython中测试记录如下:
In [21]: %time%run dict.py{0:1.1356172702418055, 1: -0.24725099335195655, 2: -0.8566028472732841, 3:-0.7027863981377108, 4: 0.8563383373116604, 5: 1.4790260114125025, 6:0.45741003038960254}Wall time: 0 ns In [22]: %time%run dict.py{0:0.4634308244997993, 1: -0.2169481701227914, 2: 1.844213869777202, 3:-1.09428552819743, 4: -0.3162553722440559, 5: 0.35052990092285824, 6:-1.0779260478165211}Wall time: 0 ns
这结果有点……
确实,这么简单的语句能够执行多少时间呢!何况现在用的本子还是标压处理器,又是I7计算最强芯。好,接下来改造一下,改成循环:
#!/usr/bin/python import numpy as npfrom numpy.randomimport randn for i inrange(1000):data = {i : randn() for i in range(7)}print(data)
以上代码存储到新文件之后,在IPython中进行测试与记录。眼前闪过一大片输出,拷贝全部的记录不太可能了,截取部分结果如下:
{0:-0.8346562430694008, 1: -0.5081226699243429, 2: 0.14690620427134915, 3:-1.1947018796604227, 4: 0.5299884594565932, 5: -0.11730239691529774, 6:-0.008304349615949396}{0:-0.5004558540946741, 1: -2.239882398599743, 2: -0.4877611466394901, 3:0.04679029941320335, 4: -0.04061984884439187, 5: -0.18026780798066566, 6:0.2617579789690715}{0:-0.8498496249579838, 1: -0.34650772255315343, 2: -0.7067822075542513, 3:0.4675343777714329, 4: -2.095049716609193, 5: -1.9396619017424426, 6:1.4723754138476228}{0:1.0829454562962688, 1: 0.3658593642766029, 2: 0.7825005873884392, 3:-0.7024245957641886, 4: -0.9083494908408439, 5: -0.5225361343604294, 6:0.2780526056846729}Wall time: 2.67 s
这次的执行结果确实是挺长的,个人觉得主要的瓶颈应该还是在输出功能上吧!在用timeit测试一下,看看结果是否有大的变化。部分记录结果如下:
{0:1.1881922773474327, 1: 2.095703415950821, 2: 0.7768251617416795, 3:-0.3639801567794642, 4: -1.2155069020886828, 5: 0.05454831526380187, 6:0.521994301720664}{0:0.0962573073179745, 1: -0.6917641905037167, 2: 1.021197433972855, 3:0.4155701479521505, 4: 2.393391538898768, 5: 1.3755258048747323, 6:-0.5540780961303758}{0:-0.418199398478115, 1: 1.1973929026808094, 2: -0.3243683593668846, 3:-1.7765735471011064, 4: -1.1567528174241677, 5: -2.297151750515544, 6:1.6966820033283279}1 loop, best of 3:1.68 s per loop
新闻热点
疑难解答