最早见过手写的,类似于下面这种:

  1 import datetime
2
3 def time_1():
4 begin = datetime.datetime.now()
5 sum = 0
6 for i in xrange(10000000):
7 sum = sum + i
8 end = datetime.datetime.now()
9 return end-begin
10
11 print time_1()

输出如下:

➜  Python python time_1.py
0:00:00.280797

另外一种方法是使用timeit模块,使用方法如下:

In [5]: import timeit

In [6]: timeit.timeit("sum(range(100))")
Out[6]: 1.2272648811340332

还可以在命令行上使用这种timeit模块,如下:

➜  Python python -m timeit -s"import time_1 as t" "t.time_1()"
0:00:00.282044 10 loops, best of 3: 279 msec per loop

注意:timeit模块会多次运行程序以获得更精确的时间,所以需要避免重复执行带来的影响。比方说x.sort()这种操作,因为第一次执行之后,后边已经是排好的了,准确性就收到了影响。

还有一种方法是使用cProfile模块,代码如下,名字为time_1.py:

  1 import datetime
2
3 def time_1():
4 begin = datetime.datetime.now()
5 sum = 0
6 for i in xrange(10000000):
7 sum = sum + i
8 end = datetime.datetime.now()
9 return end-begin
10
11 if __name__ == '__main__':
12 print time_1()
13
14 import cProfile
15 cProfile.run('time_1()')

运行程序结果如下:  

➜  Python python time_1.py
0:00:00.282828
2 function calls in 0.000 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} Traceback (most recent call last):
File "time_1.py", line 15, in <module>
cProfile.run('main()')
File "/usr/lib/python2.7/cProfile.py", line 29, in run
prof = prof.run(statement)
File "/usr/lib/python2.7/cProfile.py", line 135, in run
return self.runctx(cmd, dict, dict)
File "/usr/lib/python2.7/cProfile.py", line 140, in runctx
exec cmd in globals, locals
File "<string>", line 1, in <module>
NameError: name 'main' is not defined
➜ Python vi time_1.py
➜ Python python time_1.py
0:00:00.284642
5 function calls in 0.281 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.281 0.281 <string>:1(<module>)
1 0.281 0.281 0.281 0.281 time_1.py:3(time_1)
2 0.000 0.000 0.000 0.000 {built-in method now}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

一开始代码里最后一行写的是cProfile.run('main()'),提示没有main(),将main()改成函数名字就可以了

这里是最简单的应用,具体大家可以去看看文档,或者直接help(xxx)  

好物、羊毛线报群,需要的可加QQ群 1049623906

分析python程序运行时间的几种方法的更多相关文章

  1. 检测Java程序运行时间的2种方法(高精度的时间[纳秒]与低精度的时间[毫秒])

    第一种是以毫秒为单位计算的. 代码如下: long startTime=System.currentTimeMillis(); //获取开始时间 doSomeThing(); //测试的代码段 lon ...

  2. C#计算一段程序运行时间的三种方法

    第一种方法利用System.DateTime.Now: static void SubTest() { DateTime beforDT = System.DateTime.Now; //耗时巨大的代 ...

  3. 横向对比分析Python解析XML的四种方式

    横向对比分析Python解析XML的四种方式 在最初学习PYTHON的时候,只知道有DOM和SAX两种解析方法,但是其效率都不够理想,由于需要处理的文件数量太大,这两种方式耗时太高无法接受. 在网络搜 ...

  4. 【Qt】实现程序重启的两种方法

    Qt5/PyQt5 实现程序重启的两种方法 前言 最近在写一个开源项目,需要实现一个程序自动重启的功能.尝试了好几种方式,效果均不太理想. 一开始的实现思路是,记为思路一吧.大概就是写一些 shell ...

  5. Python下载网页的几种方法

    get和post方式总结 get方式:以URL字串本身传递数据参数,在服务器端可以从'QUERY_STRING'这个变量中直接读取,效率较高,但缺乏安全性,也无法来处理复杂的数据(只能是字符串,比如在 ...

  6. 改善C#程序,提高程序运行效率的50种方法

    改善C#程序,提高程序运行效率的50种方法   转自:http://blog.sina.com.cn/s/blog_6f7a7fb501017p8a.html 一.用属性代替可访问的字段 1..NET ...

  7. Python字符串连接的5种方法

    总结了一下Python字符串连接的5种方法: 加号 第一种,有编程经验的人,估计都知道很多语言里面是用加号连接两个字符串,Python里面也是如此直接用 "+" 来连接两个字符串: ...

  8. 用Python计算幂的两种方法,非递归和递归法

    用Python计算幂的两种方法: #coding:utf-8 #计算幂的两种方法.py #1.常规方法利用函数 #不使用递归计算幂的方法 """ def power(x, ...

  9. Python保留小数的几种方法

    Python保留小数的几种方法 1.使用字符串格式化 print("%.2f"%a) 2.使用round内置函数 round(num,2) 3.使用Decimal模块 from d ...

随机推荐

  1. leetcode - 位运算题目汇总(上)

    最近在看位运算的知识,十分感叹于位运算的博大精深,正好leetcode有 Bit Manipulation 的专题,正好拿来练练手. Subsets 给出一个由不同的数字组成的数组,枚举它的子数组(子 ...

  2. .NET MVC AjaxHelper

    我们首先必须开启 非入侵式 Ajax:导入Jquery和unobtrusiveAjax文件 已经默认开启客户端验证 和 非侵入式js <add key="ClientValidatio ...

  3. ModernUI教程:定义一个Logo

    ModernWindow的标题栏包含了一块区域用来显示自定义的窗体Logo: 这个窗体logo通过ModernWindow.LogoData属性来设置.这个属性是几何类型数据支持Path.Data m ...

  4. MATLAB中取整函数(fix, floor, ceil, round)的使用

    MATLAB取整函数 1)fix(x) : 截尾取整. >> fix( [3.12 -3.12]) ans = 3    -3(2)floor(x):不超过x 的最大整数.(高斯取整) & ...

  5. BroadcastReceiver之发送自定义无序广播

    首先,发送一个自定义广播:(用sendBroadcast(intent)发送一条无序广播) public void click(View v){ Intent intent = new Intent( ...

  6. linux初级,连网

    第一次写,今天刚好装上centos,然后就玩装一些软件,但要联网,所以琢磨了半天连网,下面总结下今天积累的一些知识点吧! 首先需要查看电脑有没有装驱动:ifconfig -a, 看有没有eh0(网卡) ...

  7. ubuntu中安装VMWare tools

    在进入VMware Workstation之后找到虚拟机然后选择安装VMWare Tools 在下载的安装包中找到linux.iso,比如我的是C:\Program Files (x86)\VMwar ...

  8. 微信公众平台消息接口开发之微信浏览器HTTP_USER_AGENT判断

    在微信公众平台的开发过程中,我们有时需要开发网页并判断是否是是来自微信浏览器访问,本文介绍如何做出这一判断. 一.$_SERVER数组 $_SERVER 是一个包含了诸如头信息(header).路径( ...

  9. C# EventHandler and Delegate(委托的使用)

    委托的声明 public delegate void MyDelegate(string str); 注 1.委托的定义和方法的定义类似,只是在前面加了一个delegate,但委托不是方法,它是一种特 ...

  10. MyBatis_ibatis和mybatis的区别【转】

    1. ibatis3.*版本以后正式改名为mybaits,它也从apache转到了google code下:也就是说ibatis2.*,mybatis3.*. 2. 映射文件的不同 ibatis的配置 ...