<file_sep># -*- coding: utf-8 -*-
import re
import os
import time
def APP_traffic(App_name):
	if  App_name.find(':') != -1 or App_name.find('/') != -1:
		print 'error'
		raise ValueError('App_name error')
	a = os.popen('adb shell ps').readlines()
	lis = []
	for k in xrange(len(a)):
		if a[k].find('%s'%(App_name)) != -1 and a[k].find(':') == -1 and a[k].find('/') == -1:
			for x in a[k].split(' '):
				if  x != '':
					lis.append(x)
			Pid = lis[1]
			break        
	lis = []
	b = os.popen('adb shell cat /proc/%s/status'%(Pid)).readlines()
	for k in xrange(len(b)):
		if b[k].find('Uid:') != -1:
			for x in b[k].split('\t'):
				lis.append(x)
			Uid = lis[1]
			break
	#发送数据
	data = os.popen('adb shell cat /proc/uid_stat/%s/tcp_snd'%(Uid)).readlines()
	tcp_snd = re.findall(r'\d+',''.join(data[0]))
	#接收数据
	data = os.popen('adb shell cat /proc/uid_stat/%s/tcp_rcv'%(Uid)).readlines()
	tcp_rcv = re.findall(r'\d+',''.join(data[0]))
	data_dict = {	'tcp_snd':int(''.join(tcp_snd)),
					'tcp_rcv':int(''.join(tcp_rcv)),
					'Pid':Pid,
					'Uid':Uid    }
	return data_dict
def link():
	#Check the connection status
	link = ''.join(os.popen('adb devices').readlines()[1])
	#print link
	try:
		assert link.find('device') !=- 1,u'error'
	except:
		print 'off line'
		raise ValueError('off line')


if __name__ == '__main__':

	all_snd = []
	all_rcv = []

	name = 'com.tencent.tmgp.sgame'
	t = 600
	
	try:
		import sys,getopt
		opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
		for op, value in opts:
			if op == '-p':
				#print value
				name = value
			if op == '-t':
				#print value
				t = value
			if op == '-l':
				path1 = value + 'data_%s'%( str(time.strftime("%m%d", time.localtime())))
	except:
		raise ValueError('error')
	
	try:
		os.makedirs('%s'%(path1))
	except:
		pass
	
	print name

	print 'start!'

	#Check the connection status
	link()

	a = APP_traffic(name)
	start_snd = float(a['tcp_snd']) / 1024
	start_rcv = float(a['tcp_rcv']) / 1024
	time.sleep(1)
	for T in range(int(t)):

		try:
			link()
		except:
			break

		print T+1
		a = APP_traffic(name)
		end_snd = float(a['tcp_snd']) / 1024
		end_rcv = float(a['tcp_rcv']) / 1024

		all_snd.append(float('%.2f'%(end_snd - start_snd)))
		all_rcv.append(float('%.2f'%(end_rcv - start_rcv)))

		print 'tcp_snd:' ,'%.2f'%(end_snd - start_snd) ,'KB'
		print 'tcp_rcv:' ,'%.2f'%(end_rcv - start_rcv) ,'KB'

		start_snd = end_snd 
		start_rcv = end_rcv

		time.sleep(0.5)

	print 'snd + ',sum(all_snd)
	print 'rcv + ',sum(all_rcv)
		
	print '生成数据文件...'
	tiems = time.strftime("%m%d-%H%M%S", time.localtime())
	File = open( r'%s'%(path1) + r'\Data_Flow_Data%s.txt'%(tiems),'w')
	#File = open( 'c:\Data_Flow_Data%s.txt'%(tiems) ,'w')
	File.write( 'SND' + ' ' + 'RCV' + '\n' )
	for i in range( len(all_snd) ):
		File.write( str(all_snd[i]) + ';' + str(all_rcv[i]) + '\n' )
	File.close()
<file_sep># -*- coding: utf-8 -*-
import os
import time
import re
 
def CPU(app_name='',path='c:/'):

	def Log_file(data):
		try:
			print u'Generate data files...'
			tiems = time.strftime("%m%d-%H%M%S", time.localtime())
    		File = open( r'%s'%(path) + r'\CpuData%s.txt'%(tiems),'w' )
			for i in range(len(data)):
				File.write(str(data[i])+'\n')
			File.close()
			print u'Save the file successfully'
		except:
			print 'Save file failed'

	cut_formula = re.compile(r'\s+')

	#存放CPU数据的数组
	cpu_array = []
	
	try:
		#增加变量来控制找不到包名后不要过早报错
		p = 0
		#增加变量控制每10次循环检查一遍连接
		i = 0
		while 1>0:			
			
			if  i == 0:
				link = ''.join(os.popen('adb devices').readlines()[1])
				try:
	            	#表达式=-1说明没找到设备
					assert link.find('device')!=-1,u'error'
					#循环N次后检查连接
					i = 10
				except:
					print 'Equipment broken links'
					raise ValueError('Equipment broken linksd')
			#i 减到 0 检查一次连接		
			i = i - 1

			a = os.popen('adb shell top -m 80 -n 1 -s cpu').readlines()
			#print a
			for i in range(len(a)):
				if ''.join(a[i]).find('%s'%app_name) != -1 and ''.join(a[i]).find(':') == -1:
					b = ''.join(a[i])
					#print b
					#连接成功就重置控制变量P
					p = 0
					break
				# i 是从0开始的
				elif i == len(a)-1:	
					#重连5次后报错
					if p == 5:
						print('No app detected')
						raise ValueError('No app detected')
					else:
						p = p + 1
						print 'disconnect',p
			# re.sub(): b 中的 空格符 替换成“？” ，分割字符串 b
			#a    b c->a?b?c
			#a?b?c->['a','b','c']
			#print '1',b
			try:
				if  p == 0:
					b = ''.join(re.sub(cut_formula,'?', b)).split('?')
					#print '2',b
					for k in b:
						if k.find('%') != -1:
							k = re.match(r'\d+',k).group()
							cpu_array.append(k) 
							print k,'%'
			except:
				if p == 5:
					raise ValueError('b')
				else:
					p = p + 1
			time.sleep(1)
	except:
		print 'Device or file can not be found'
		Log_file(cpu_array)

if __name__ == '__main__':

	import sys,getopt
	opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
	for op, value in opts:
		if op == '-p':
 		    #print value
 		    Name = value
 		if op == '-t':
 		    #print value
 		    T = value
 		if op == '-l':
 		    path1 = value + 'data_%s'%(str(time.strftime("%m%d", time.localtime())))
	try:
		os.makedirs('%s'%(path1))
	except:
		pass

	CPU(app_name = Name ,path = path1)
<file_sep># -*-coding: utf-8 -*-
import os
from uiautomator import Device
import subprocess
import time
import sys, getopt
def record_and_untied(b,x,y,a):
	#2000000
	os.popen('adb shell am force-stop %s'%(a))
	child = subprocess.Popen('adb shell screenrecord --bit-rate 6000000 /sdcard/record%d.mp4'%(b))
	time.sleep(1)
	d.click(x, y)
	time.sleep(2)
	d.press("home")
	time.sleep(0.5)
	child.kill()
	child.wait()
	time.sleep(1)
	os.makedirs( r'%s'%(path1) + r'\%d'%(b))
	print 'mkdir-'*20
	child = subprocess.Popen(['adb','pull','sdcard/record%d.mp4'%(b), r'%s'%(path1) + r'\%d.mp4'%(b)])
	child.wait()	
	ffmpeg_path = os.path.split(os.path.realpath(__file__))[0] + '\\ffmpeg.exe'
	subprocess.Popen('%s'%(ffmpeg_path) + r' -i %s\%d.mp4 -f image2 -vf fps=fps=50 %s\%d'%(path1,b,path1,b)+r'/%d.jpg')
	if b == 3:
		time.sleep(10)
		sys.exit(0)
	else:
		child.wait()
if __name__ == '__main__':

	global path1

	opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
	for op, value in opts:
		if op == '-c':
			X = int(value.split(',')[0])
			Y = int(value.split(',')[1])
		if op == '-d':
			#print value
			PHONE_ID = value
		if op == '-l':
			times = '\\jiezhen' + str(time.strftime("%m%d-%H%M%S", time.localtime()))
			path1 = value + 'data_%s'%(str(time.strftime("%m%d", time.localtime()))) + times
		if op == '-p':
			app = value
	d = Device(PHONE_ID)
	print X,Y
	print d.info


	try:
		pass
		#os.makedirs( r'%s'%(path1) + r'\jiezhen')
	except:
		pass

	for k in xrange(1,4):
		record_and_untied(k, X, Y,a=app)<file_sep># -*- coding: utf-8 -*-
import re
#import pylab as pl
import os
import time
import sys,getopt
def Pss():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
        for op, value in opts:
            if op == '-p':
                #print value
                Name = value
            if op == '-t':
                #print value
                T = value
            if op == '-l':
                path1 = value + 'data_%s'%(str(time.strftime("%m%d", time.localtime())))
    except:
        Name = 'com.taobao.idlefish' 
        T = 1800
        path1 = r'F:\Jenkins\workspace\Performance_Testing'
        raise ValueError('error')
    try:
        os.makedirs('%s'%(path1))
    except:
        pass
    system_version = ''.join(os.popen('adb shell getprop ro.build.version.release').readlines())
    system_version = int( ''.join(system_version.split('.')[:2]) )
    print system_version
    pss = []
    try:
        for jc in range(int(T)):
            link=''.join(os.popen('adb devices').readlines()[1])
            try:
                assert link.find('device') !=- 1,u'error'
            except:
                print '连接失败'
                break
            a=''.join(os.popen('adb shell dumpsys meminfo %s'%Name).readlines())
            
            if  system_version <= 70:
                #安卓7.0及以下
                a=a.split('\r\n') 
            else:
                #安卓7.1
                a=a.split('\n')
            for ck in a:
                if ck.find('TOTAL') != -1 and ck.find(':') == -1:
                    p=re.findall(r'\d+',ck)
                    print p[0]
                    pss.append(int(p[0]))
            print jc + 1
            time.sleep(0.40)
        print '录制完毕，正在处理...'
    except:
        print 'error'
    #x=range(0,len(pss))
    print '生成数据文件...'
    tiems = time.strftime("%m%d-%H%M%S", time.localtime())
    File = open( r'%s'%(path1) + r'\PssData%s.txt'%(tiems),'w' )
    for i in range(len(pss)):
        #File.write(str(x[i])+' '+str(pss[i])+'\n')
        File.write(str(pss[i])+'\n')
    File.close()
    
    #print type(pss[0])
    avg = sum(pss) / len(pss)
    print 'average:',avg

    '''
    print '生成图表...'
    pl.xlabel('')
    pl.ylabel('P S S')
    pl.title('P S S Graphic')
    pl.plot(x,pss,'y')#这个是pss
    pl.show()
    '''

if __name__=='__main__':



    s = time.time()
    Pss()
    e = time.time()
    print 'time:',e-s<file_sep>import subprocess
import getopt
import sys
try:
	opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
except:
	pass

try:
	import urllib3
except:
	child = subprocess.Popen('python -m pip install urllib3 --trusted-host 10.75.22.30 -i http://10.75.22.30:8088/123/')
	child.wait()

try:
	import uiautomator
except:
	child = subprocess.Popen('python -m pip install uiautomator --trusted-host 10.75.22.30 -i http://10.75.22.30:8088/123/')
	child.wait()
<file_sep># -*- coding: utf-8 -*-
import re
#import pylab as pl
import os
import time
import gc

def Fps(T,Name,path2):
    print "请确保开发者选项中的GPU呈现模式分析  调整正确"
    system_version = ''.join(os.popen('adb shell getprop ro.build.version.release').readlines())
    system_version = int( ''.join(system_version.split('.')[:1]) )
    print system_version
    if system_version < 5:
        lv=3
    else:
        lv=4
    n=[]
    for jc in range(int(T)):
        link=''.join(os.popen('adb devices').readlines()[1])
        try:
            assert link.find('device')!=-1,u'error'
        except:
            print '连接失败'
            break
        print jc+1
        c=''
        a=''.join(os.popen('adb shell dumpsys gfxinfo %s'%Name).readlines())
        a=a.split('\n')
        for i in a:
            if i.lower().islower() == False:
                c=c+i+'\n'
        n.append(re.findall(r'\d+\.\d+',c))
        #print n
        del a
        del c
        gc.collect()
        time.sleep(1.65)
    s=[]
    for m in n:
        for mm in m:
            s.append(mm)
    del n
    gc.collect()
    e=[]
    k=0
    for i in range(len(s)):
        if (i+1)%lv==0:
            k=k+float(s[i])
            e.append(float('%.2f'%k))
            k=0
        else:
            k=k+float(s[i])
    '''
    x=range(0,len(e))

    sta=[]
    for i in range(len(e)):
        sta.append(16)
    '''
    print '生成数据文件...'
    tiems = time.strftime("%m%d-%H%M%S", time.localtime())
    File = open( r'%s'%(path2) + r'\FpsData%s.txt'%(tiems),'w')
    for i in range(len(e)):
        #File.write(str(x[i])+' '+str(e[i])+'\n')
        File.write(str(e[i])+'\n')
    File.close()
    '''
    print '生成图表...'
    pl.xlabel('')
    pl.ylabel('F P S')
    pl.title('F P S Graphic')
    pl.plot(x,e,'y')#这个是FPS
    pl.plot(x,sta,'r')#这个是16ms线
    pl.show()
    '''
if __name__=='__main__':
    
    name =''
    t = ''
    try:
        import sys,getopt
        opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
        for op, value in opts:
            if op == '-p':
                #print value
                name = value
            if op == '-t':
                #print value
                t = value
            if op == '-l':
                path1 = value + 'data_%s'%( str(time.strftime("%m%d", time.localtime())))
    except:
        print 'error'
        name = 'com.taobao.idlefish' 
        t = 180
        raise ValueError('error')

    try:
        os.makedirs('%s'%(path1))
    except:
        pass
        
    Fps(t,name,path1)