为什么Python程序cpu占用率高不怎么占用CPU资源

10种检测Python程序运行时间、CPU和内存占用的方法
作者:Marina Mele
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了10种检测Python程序运行时间、CPU和内存占用的方法,包括利用Python装饰器或是外部的Unix Shell命令等,需要的朋友可以参考下
在运行复杂的Python程序时,执行时间会很长,这时也许想提高程序的执行效率。但该怎么做呢?
首先,要有个工具能够检测代码中的瓶颈,例如,找到哪一部分执行时间比较长。接着,就针对这一部分进行优化。
同时,还需要控制内存和CPU的使用,这样可以在另一方面优化代码。
因此,在这篇文章中我将介绍7个不同的Python工具,来检查代码中函数的执行时间以及内存和CPU的使用。
1. 使用装饰器来衡量函数执行时间
有一个简单方法,那就是定义一个装饰器来测量函数的执行时间,并输出结果:
import time
from functools import wraps
def fn_timer(function):
@wraps(function)
def function_timer(*args, **kwargs):
t0 = time.time()
result = function(*args, **kwargs)
t1 = time.time()
print ("Total time running %s: %s seconds" %
(function.func_name, str(t1-t0))
return result
return function_timer
接着,将这个装饰器添加到需要测量的函数之前,如下所示:
def myfunction(...):
例如,这里检测一个函数排序含有200万个随机数字的数组所需的时间:
def random_sort(n):
return sorted([random.random() for i in range(n)])
if __name__ == "__main__":
random_sort(2000000)
执行脚本时,会看到下面的结果:
Total time running random_sort: 1. seconds
2. 使用timeit模块
另一种方法是使用timeit模块,用来计算平均时间消耗。
执行下面的脚本可以运行该模块。
python -m timeit -n 4 -r 5 -s "import timing_functions" "timing_functions.random_sort(2000000)"
这里的timing_functions是Python脚本文件名称。
在输出的末尾,可以看到以下结果:
4 loops, best of 5: 2.08 sec per loop
这表示测试了4次,平均每次测试重复5次,最好的测试结果是2.08秒。
如果不指定测试或重复次数,默认值为10次测试,每次重复5次。
3. 使用Unix系统中的time命令
然而,装饰器和timeit都是基于Python的。在外部环境测试Python时,unix time实用工具就非常有用。
运行time实用工具:
$ time -p python timing_functions.py
输出结果为:
Total time running random_sort: 1. seconds
第一行来自预定义的装饰器,其他三行为:
&&& real表示的是执行脚本的总时间
&&& user表示的是执行脚本消耗的CPU时间。
&&& sys表示的是执行内核函数消耗的时间。
注意:根据,内核是一个计算机程序,用来管理软件的输入输出,并将其翻译成CPU和其他计算机中的电子设备能够执行的数据处理指令。
因此,Real执行时间和User+Sys执行时间的差就是消耗在输入/输出和系统执行其他任务时消耗的时间。
4. 使用cProfile模块
如果想知道每个函数和方法消耗了多少时间,以及这些函数被调用了多少次,可以使用cProfile模块。
$ python -m cProfile -s cumulative timing_functions.py
现在可以看到代码中函数的详细描述,其中含有每个函数调用的次数,由于使用了-s选项(累加),最终结果会根据每个函数的累计执行时间排序。
读者会发现执行脚本所需的总时间比以前要多。这是由于测量每个函数的执行时间这个操作本身也是需要时间。
5. 使用line_profiler模块
line_profiler模块可以给出执行每行代码所需占用的CPU时间。
首先,安装该模块:
$ pip install line_profiler
接着,需要指定用@profile检测哪个函数(不需要在代码中用import导入模块):
def random_sort2(n):
l = [random.random() for i in range(n)]
if __name__ == "__main__":
random_sort2(2000000)
最好,可以通过下面的命令获得关于random_sort2函数的逐行描述。
$ kernprof -l -v timing_functions.py
其中-l表示逐行解释,-v表示表示输出详细结果。通过这种方法,我们看到构建数组消耗了44%的计算时间,而sort()方法消耗了剩余的56%的时间。
同样,由于需要检测执行时间,脚本的执行时间更长了。
6. 使用memory_profiler模块
memory_profiler模块用来基于逐行测量代码的内存使用。使用这个模块会让代码运行的更慢。
安装方法如下:
pip install memory_profiler
另外,建议安装psutil包,这样memory_profile会运行的快一点:
$ pip install psutil
与line_profiler相似,使用@profile装饰器来标识需要追踪的函数。接着,输入:
$ python -m memory_profiler timing_functions.py
脚本的执行时间比以前长1或2秒。如果没有安装psutil包,也许会更长。
从结果可以看出,内存使用是以MiB为单位衡量的,表示的mebibyte(1MiB = 1.05MB)。
7. 使用guppy包
最后,通过这个包可以知道在代码执行的每个阶段中,每种类型(str、tuple、dict等)分别创建了多少对象。
安装方法如下:
$ pip install guppy
接着,将其添加到代码中:
from guppy import hpy
def random_sort3(n):
hp = hpy()
print "Heap at the beginning of the functionn", hp.heap()
l = [random.random() for i in range(n)]
print "Heap at the end of the functionn", hp.heap()
if __name__ == "__main__":
random_sort3(2000000)
运行代码:
$ python timing_functions.py
可以看到输出结果为:
通过在代码中将heap()放置在不同的位置,可以了解到脚本中的对象创建和删除操作的流程。
如果想学习更多关于Python代码速度优化方面的知识,我建议你去读这本书《.》
希望这篇文章能偶帮到你!^_^
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具jiege123 的BLOG
用户名:jiege123
文章数:78
评论数:18
访问量:96741
注册日期:
阅读量:5863
阅读量:12276
阅读量:401496
阅读量:1091178
51CTO推荐博文
&&下面是一段统计linux服务器单个核cpu使用率的python代码,大家可以看看,如果有bug请留言。# -*- coding: cp936 -*-
import re,time
def _read_cpu_usage():
&&&&&&&&"""Read the current system cpu usage from /proc/stat"""
&&&&&&&&statfile = "/proc/stat"
&&&&&&&&cpulist = []
&&&&&&&&try:
&&&&&&&&&&&&&&&&f = open(statfile, 'r')
&&&&&&&&&&&&&&&&lines = f.readlines()
&&&&&&&&except:
&&&&&&&&&&&&&&&&print "error:无法打开文件%s,系统无法继续运行。" % (statfile)
&&&&&&&&&&&&&&&&return []
&&&&&&&&for line in lines:
&&&&&&&&&&&&&&&&tmplist = line.split()
&&&&&&&&if len(tmplist) & 5:
&&&&&&&&&&&&&&&&continue
&&&&&&&&for b in tmplist:
&&&&&&&&&&&&&&&&m = re.search(r'cpu\d+',b)
&&&&&&&&&&&&&&&&if m is not None:
&&&&&&&&&&&&&&&&&&&&&&&&cpulist.append(tmplist)
&&&&&&&&f.close()
&&&&&&&&return cpulist
def get_cpu_usage():
&&&&&&&&cpuusage = {}
&&&&&&&&cpustart = {}
&&&&&&&&cpuend = {}
&&&&&&&&linestart = _read_cpu_usage()
&&&&&&&&if not linestart:
&&&&&&&&&&&&&&&&return 0
&&&&&&&&for cpustr in linestart:
&&&&&&&&&&&&&&&&usni=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])+long(cpustr[5])+long(cpustr[6])+long(cpustr[7])+long(cpustr[4])
&&&&&&&&&&&&&&&&usn=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])
&&&&&&&&&&&&&&&&cpustart[cpustr[0]] = str(usni)+":"+str(usn)
&&&&&&&&sleep = 2
&&&&&&&&time.sleep(sleep)
&&&&&&&&lineend = _read_cpu_usage()
&&&&&&&&if not lineend:
&&&&&&&&&&&&&&&&return 0
&&&&&&&&for cpustr in lineend:
&&&&&&&&&&&&&&&&usni=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])+long(cpustr[5])+long(cpustr[6])+long(cpustr[7])+long(cpustr[4])
&&&&&&&&&&&&&&&&usn=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])
&&&&&&&&&&&&&&&&cpuend[cpustr[0]] = str(usni)+":"+str(usn)
&&&&&&&&for line in cpustart:
&&&&&&&&&&&&&&&&start = cpustart[line].split(':')
&&&&&&&&&&&&&&&&usni1,usn1 = float(start[0]),float(start[1])
&&&&&&&&&&&&&&&&end = cpuend[line].split(':')
&&&&&&&&&&&&&&&&usni2,usn2 = float(end[0]),float(end[1])
&&&&&&&&&&&&&&&&cpuper=(usn2-usn1)/(usni2-usni1)
&&&&&&&&&&&&&&&&cpuusage[line] = int(100*cpuper)
&&&&&&&&return cpuusage
if __name__ == '__main__':
&&&&&&&&a = get_cpu_usage()
&&&&&&&&print a执行结果,如截图:650) this.width=650;" src="../attachment/324928.jpg" border="0" alt="" />本文出自 “” 博客,请务必保留此出处
了这篇文章
类别:┆阅读(0)┆评论(0)Python获取单个程序CPU使用情况趋势图
投稿:junjie
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Python获取单个程序CPU使用情况趋势图,本文使用matplotlib将数据可视化,需要的朋友可以参考下
本文定位:已将CPU历史数据存盘,等待可视化进行分析,可暂时没有思路。
前面一篇文章()提到过在linux下如何用python将top命令的结果进行存盘,本文是它的后续。
python中我们可以用matplotlib很方便的将数据可视化,比如下面的代码:
import matplotlib.pyplot as plt
list1 = [1,2,3]
list2 = [4,5,9]
plt.plot(list1,list2)
plt.show()
执行效果如下:
上面只是给plot函数传了两个list数据结构,show一下图形就出来了……哈哈,很方便吧!
获取CPU趋势图就用这个了!
可我们现在得到的数据没那么友好,比如我现在有个文件(file.txt),内容如下:
Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu(s): 7.7%us, 7.7%sy, 0.0%ni, 76.9%id, 0.0%wa, 0.0%hi, 7.7%si, 0.0%st
Cpu(s): 0.0%us, 9.1%sy, 0.0%ni, 90.9%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu(s): 9.1%us, 0.0%sy, 0.0%ni, 90.9%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu(s): 8.3%us, 8.3%sy, 0.0%ni, 83.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu(s): 0.0%us, 9.1%sy, 0.0%ni, 90.9%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
其中,第一列为时间,第六列为CPU的idle值。
要从这组数据中得出CPU使用情况趋势图,我们就要做些工作了。
下面是代码,这里提供一个思路,需要的朋友拷回去改一下吧:
#coding:utf-8
&&&&& File&&&&& : cpuUsage.py
&&&&& Author&&& : Mike
&&&&& E-Mail&&& : Mike_
import matplotlib.pyplot as plt
import string
def getCpuInfData(fileName):
&&& ret = {}
&&& f = open(fileName,"r")
&&& lineList = f.readlines()
&&& for line in lineList:
&&&&&&& tmp = line.split()
&&&&&&& sz = len(tmp)
&&&&&&& t_key = string.atoi(tmp[0]) # 得到key
&&&&&&& t_value = 100.001-string.atof(line.split(':')[1].split(',')[3].split('%')[0]) # 得到value
&&&&&&& print t_key,t_value&&&
&&&&&&& if not ret.has_key(t_key) :
&&&&&&&&&&& ret[t_key] = []
&&&&&&& ret[t_key].append(t_value)
&&& f.close()
&&& return ret
retMap1 = getCpuInfData("file.txt")
# 生成CPU使用情况趋势图
list1 = retMap1.keys()
list1.sort()
list2 = []
for i in list1:list2.append(retMap1[i])
plt.plot(list1,list2)
plt.show()
好,就这些了,希望对你有帮助。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 程序cpu占用率高 的文章

 

随机推荐