#coding: utf-8
'''
Created on 2016-5-22
@author: wangyongqi
'''
import numpy as np
import matplotlib.pyplot as plt
# import pylib
import os,time
"""
注意:场景内存、CPU标题
修改场景标题后,产生的图标即显示修改后的内容
"""
memcpu_title =
raw_input("编辑测试场景内容,用于曲线图中标题显示,标题不宜太长:".decode('utf-8').encode('gbk'))
print memcpu_title
memcpu_title=memcpu_title.decode("gbk")
# memcpu_title=u"取景页面添加萌颜后占用"
testpath=[]
for i in range(10):
testpath0="E:\\00uiautomatorreport\\"+str(i)
if
os.path.exists(testpath0):
testpath.append(testpath0)
print testpath
# testpath1="E:\\00uiautomatorreport\\1"
# testpath2="E:\\00uiautomatorreport\\2"
# testpath3="E:\\00uiautomatorreport\\3"
timeStamp=int(time.time())
timeArray = time.localtime(timeStamp)
FileTime = time.strftime("%Y_%m_%d_%H_%M_%S", timeArray)
print FileTime,type(FileTime)
#遍历指定文件夹下的所有txt文件,并返回文件路径
def Txt_traverse(dir_path):
TxtPath=[]
if
os.path.isdir(dir_path)==False:
return (0,0)
else:
for dirname,dirs,filenames in
os.walk(dir_path):
filenames
dirname,'dirname',dirs,'dirs',filenames,'filenames'
for ufile
in filenames:
abspath=os.path.join(dirname,ufile)
if
os.path.splitext(abspath)[1]=='.txt' :
TxtPath.append(abspath)
print abspath
if TxtPath:
return TxtPath
# return
abspath
# f =
open(abspath)
# appname=os.path.basename(abspath).split(".")[0]
# return
f,appname
'''获取的CPU和内存长度不一时,头部补充0值,并把所有txt文件中的cpu和内存各生成一个多维数组'''
def txtCPUmem(txtpath):
try:
f=open(txtpath)
h=f.read().split()
# print h
for i in range(len(h)):
if
h[i]=="CPU":
gd=i
break
if h[0].find(":")!=-1:
numm=h[0].find(":")
pagname.append(h[0][:numm])
else:pagname.append("null")
mem=h[1:gd]
cpu= h[gd+1:]
# print "old",mem,cpu
if len(mem)!=len(cpu):
ii=abs(len(mem)-len(cpu))
if
len(mem)>len(cpu):
for i in range(ii):
cpu.insert(i,"0")
else:
for i in range(ii):
mem.insert(i,"0")
# print "new",mem,cpu
memarr.append(mem)
cpuarr.append(cpu)
except:
pass
'''多维数组中各元素长度以最短为标准截取,并求和平均,保存生成最终文件'''
def SUMarr(cpumemlist):
arrlen=[]
for i in
cpumemlist:
# print len(i)
arrlen.append(len(i))
# print arrlen
,len(arrlen)
def mininum(arrlen):
if len(arrlen)==1:
return
arrlen[0]
return min(arrlen[0],mininum(arrlen[1:]))
shortlen=mininum(arrlen)
def
delarr(arr,shortlen):
return arr[:shortlen]
shortdmem=[]
for i in
cpumemlist:
shortdmem.append(delarr(i, shortlen))
"lastshuzu",shortdmem
lastarr=[]
for j in
range(shortlen):
wsum=0
for i in shortdmem:
wsum=wsum+int(float(i[j]))
# print "zonghe:",wsum,len(shortdmem)
wsum=wsum/len(shortdmem)
lastarr.append(wsum)
# print lastarr
return
lastarr
'''生成最终的一组CPU内存数据,生成最终一组竞品CPU内存数据'''
def reporttxt(testpath):
global
pagname,memarr,cpuarr
patharr=Txt_traverse(testpath)
pagname=[]
memarr=[]
cpuarr=[]
if patharr:
for i in patharr:
txtCPUmem(i)
print memarr,cpuarr,pagname,len(memarr)
packagePATH1 = testpath+'-report\\'
if not os.path.exists(packagePATH1):
os.makedirs(packagePATH1)
txtpath=packagePATH1+"CPU_mem_info_report_"+FileTime+".txt"
f=open(txtpath,"w")
summem=SUMarr(memarr)
f.write(str(testpath[-1])+"_"+pagname[0]+":mem
")
for i in summem:
f.write(str(i/1024)+" ")
sumcpu=SUMarr(cpuarr)
f.write("CPU ")
for i in sumcpu:
f.write(str(i)+" ")
f.close()
for i in testpath:
reporttxt(i)
# reporttxt(testpath1)
# reporttxt(testpath2)
# reporttxt(testpath3)
Rmemarr=[]
Rcpuarr=[]
pagnamelist=[]
def ReportCPUmem(txtpath):
f=open(txtpath)
h=f.read().split()
print h
for i in
range(len(h)):
if h[i]=="CPU":
gd=i
if
h[0].find(":")!=-1:
numm=h[0].find(":")
pagnamelist.append(h[0][:numm])
else:pagnamelist.append("null")
mem=h[1:gd]
cpu= h[gd+1:]
"old",mem,cpu
if
len(mem)!=len(cpu):
ii=abs(len(mem)-len(cpu))
if len(mem)>len(cpu):
for i in
range(ii):
cpu.insert(i,"0")
else:
for i in
range(ii):
mem.insert(i,"0")
"new",mem,cpu
Rmemarr.append(mem)
Rcpuarr.append(cpu)
def samelenarr(cpumemlist):
arrlen=[]
for i in
cpumemlist:
# print len(i)
arrlen.append(len(i))
# print arrlen
,len(arrlen)
def mininum(arrlen):
if len(arrlen)==1:
return
arrlen[0]
return min(arrlen[0],mininum(arrlen[1:]))
shortlen=mininum(arrlen)
def
delarr(arr,shortlen):
return arr[:shortlen]
shortdmem=[]
for i in
cpumemlist:
shortdmem.append(delarr(i, shortlen))
"lastshuzu",shortdmem
return
shortdmem
for i in testpath:
ReportCPUmem(i+"-report\\CPU_mem_info_report_"+FileTime+".txt")
#
ReportCPUmem("E:\\00uiautomatorreport\\1-report\\CPU_mem_info_report.txt")
#
ReportCPUmem("E:\\00uiautomatorreport\\2-report\\CPU_mem_info_report.txt")
#
ReportCPUmem("E:\\00uiautomatorreport\\3-report\\CPU_mem_info_report.txt")
# print Rmemarr,Rcpuarr
LASTMEM=samelenarr(Rmemarr)
LASTCPU=samelenarr(Rcpuarr)
# print max(mem),type(max(mem))
# maxy=int(max(cpu))+10
def PngReport(LASTCPUMEM,Strtitle):
X_X=len(LASTCPUMEM[0])
x=[]
# legendall=[]
k=0
for i in
range(X_X):
x.append(i)
# print x
fig=plt.figure(figsize=(10, 5))
ax= fig.add_subplot(111)
for i in
LASTCPUMEM:
# ax= fig.add_subplot(111)
ax.plot(x,i,label=pagnamelist[k],linewidth=2)
k=k+1
# legendall.append(plotlegend)
# plt.plot(x,y)
# plt.xlim(0)
# plt.ylim(0)
plt.xlabel("time(s)")
plt.ylabel("value")
plt.title(memcpu_title+Strtitle,fontproperties='SimHei',fontsize=25)
#设置图例在坐标系的外围
box=ax.get_position()
ax.set_position([box.x0,
box.y0, box.width* 0.8 , box.height])
# ax.legend(loc=1)
ax.legend(loc="upper
left",bbox_to_anchor=(1, 0.5),ncol=1)
"box1111111111111",box.x0,box.y0,box.width,box.height
# plt.legend(legendall,('hertwet','ewertwertew','ertewtewrl'),'best',
numpoints=1)
plt.savefig("E:\\00uiautomatorreport\\"+Strtitle+"info_"+FileTime+".png")
# plt.show()
PngReport(LASTMEM," memory(M)")
PngReport(LASTCPU," CPU(%)")
print "MEM---",LASTMEM
print "cpu---",LASTCPU
avgmem=[]
avgcpu=[]
def averageMEM(LASTMEM):
for i in LASTMEM:
s=map(int,i)
L=len(i)
print s
print "sum---------------",sum(s)/L
avgmem.append(sum(s)/L)
def averageCPU(LASTCPU):
for i in LASTCPU:
s=map(int,i)
L=len(i)
print s
print "sum---------------",sum(s)/L
avgcpu.append(sum(s)/L)
averageMEM(LASTMEM)
averageCPU(LASTCPU)
print avgcpu,avgmem
N=len(LASTMEM)
# List to tuple
Std=[]
for i in range(N):
Std.append(10)
Std =tuple(Std)
ind = np.arange(N) # the x locations for the groups
print ind
width = 0.45 # the width
of the bars
fig, ax = plt.subplots()
memMeans = tuple(avgmem)
print memMeans
rects1 = ax.bar(ind, memMeans, width, color='palegreen',
yerr=Std)
cpuMeans = tuple(avgcpu)
# womenStd = (3, 5)# print womenMeans
rects2 = ax.bar(ind+width, cpuMeans, width, color='y',
yerr=Std)
ax.set_ylabel('Scores')
ax.set_title(memcpu_title+' Average
Data',fontproperties='SimHei',fontsize=25)
ax.set_xticks(ind+width)
ax.set_xticklabels(tuple(pagnamelist))
#设置图例在坐标系的里面
# ax.legend( (rects1[0], rects2[0]), ('mem(M)',
'cpu(%)'))
#设置图例在坐标系的外围
box=ax.get_position()
ax.set_position([box.x0, box.y0, box.width* 0.8 ,
box.height])
ax.legend((rects1[0], rects2[0]), ('mem(M)',
'cpu(%)'),loc="upper left",bbox_to_anchor=(1, 0.5),ncol=1)
def autolabel(rects):
# attach some text
labels
for rect in rects:
height = rect.get_height()
print 'height',height
print 'x',rect.get_x()
print 'w',rect.get_width()
ax.text(rect.get_x()+rect.get_width()/2.,
1.001*height, '%d'%int(height),
ha='center',
va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.savefig("E:\\00uiautomatorreport\\Average_info_"+FileTime+".png")
plt.show()
# import pandas as pd
#
df=pd.read_excel("E:/0uiautomatorreport/CPU_mem_info.xls","CPU_mem")
# print df