Android Automation Performance Collection

Source: Internet
Author: User

Android Automation Performance Collection

Android function test Automation framework more, uiautomator,robotium,appium and so on. During case execution, you may want to collect performance metrics for your phone, including memory, CPU, traffic, and so on. The Android phone performance collection is simply achieved using Java+shell+bat.

Briefly

The process is simple:

    • Execute the command that collects the information before starting the automation case.
      is actually some adb shell commands, as follows:

            adb shell top -n 1| awk ‘{print $3" "$10}‘ >> cpu.dat        adb shell ps | awk ‘{print $5" "$9}‘ >> mem.dat        //android sdk level 大于16        adb shell cat /proc/uid_stat/$uid/tcp_rcv >> $uid"_recv.dat"        adb shell cat /proc/uid_stat/$uid/tcp_snd >> $uid"_snd.dat"        //android sdk level 小于16         adb shell cat /proc/$pid/net/dev | grep wlan | awk ‘{print $2" "$10}‘ >> $pid"_net.dat"  
    • It may take a long time to execute an automated case. In this process, the above command is constantly executing

    • Case execution ends, kill the command in the first step
    • Analyze the collected DAT files and use Jscharts to plot the chart
ScriptCpu

Use the top command to constantly see the CPU usage of each process

Linux

get-android-cpu.sh

    #!/bin/sh    #path--target/android-info/mem/dat    cd ../../../    mkdir -p target/android-info/cpu/dat    mkdir -p target/android-info/cpu/html    cp src/main/resources/jscharts.js target/android-info/cpu/html    cd target/android-info/cpu/dat    while true    do        adb shell top -n 1| awk ‘{print $3" "$10}‘ >> cpu.dat        sleep 15    done
Windows

Get-android-cpu.bat

    cd ..\..\jenkins\workspace\android-info-end3    mkdir target\android-info\cpu\dat    mkdir target\android-info\cpu\html    copy src\main\resources\jscharts.js target\android-info\cpu\html    cd target\android-info\cpu\dat    :run        adb shell top -n 1 | awk "{print $3\" \"$10}" >> cpu.dat        ping 127.0.0.1 -n 15 > null    goto run
Memory

Continuously view the memory footprint of each process using the PS command

Linux

get-android-mem.sh

    #!/bin/sh    #path--target/android-info/mem/dat    cd ../../../    mkdir -p target/android-info/mem/dat    mkdir -p target/android-info/mem/html    cp src/main/resources/jscharts.js target/android-info/mem/html    cd target/android-info/mem/dat    while true    do        adb shell ps | awk ‘{print $5" "$9}‘ >> mem.dat        sleep 15    done
Windows
    cd ..\..\jenkins\workspace\android-info-end3    mkdir target\android-info\mem\dat    mkdir target\android-info\mem\html    copy src\main\resources\jscharts.js target\android-info\mem\html    cd target\android-info\mem\dat    :run        adb shell ps | awk "{print $5\" \"$9}" >> mem.dat        ping 127.0.0.1 -n 15 > null    goto run
Flow

Android 4.0 or later can be used to /proc/uid_stat/$uid/tcp_rcv /proc/uid_stat/$uid/tcp_snd get up and down traffic for a program, while the following version of 4.0 is used cat /proc/$pid/net/dev to view up and down traffic. The relationship between UID and PID can be /data/system/packages.list obtained from this file.

Linux

To determine the Android API level:

    #!/bin/sh    #android 4.0以上和4.0以下方法不同    #get android sdk level    apileveltemp=`adb shell getprop | grep ro.build.version.sdk`    apilevel=${apileveltemp:25:2}    chmod +x *.sh    echo "android api level:"$apilevel    if [ $apilevel -gt 14 ]    then        ./get-android-net-gt-4.0.sh    elif [ $apilevel -lt 14 ]    then        ./get-android-net-lt-4.0.sh    fi

get-android-net-gt-4.0.sh

    #!/bin/sh    #android api level great than 14(android 4.0)    #path--target/android-info/net/dat    cd ../../../    mkdir -p target/android-info/net/dat    mkdir -p target/android-info/net/html    cp src/main/resources/jscharts.js target/android-info/net/html    cd target/android-info/net/dat    cd ..    echo "adb pull/data/system/packages.list--start"    adb pull /data/system/packages.list    cd dat    while true    do        echo "get net info from /proc/uid-stat/$uid"        for i in `adb shell ls /proc/uid_stat`        do            #delete the Enter character            uid=`echo $i | tr -d ["\r\n"]`            adb shell cat /proc/uid_stat/$uid/tcp_rcv >> $uid"_recv.dat"            adb shell cat /proc/uid_stat/$uid/tcp_snd >> $uid"_snd.dat"        done        sleep 15    done

get-android-net-lt-4.0.sh

    #!/bin/sh    #path--target/android-info/net/dat    cd ../../../    mkdir -p target/android-info/net/dat    mkdir -p target/android-info/net/html    cp src/main/resources/jscharts.js target/android-info/net/html    cd target/android-info/net/dat    #get /proc/$pid/net/dev    while true    do        #get pid        for i in `adb shell ps | awk ‘{print $2}‘`        do            pid=`echo $i | tr -d ["\r\n"]`            echo $pid            adb shell cat /proc/$pid/net/dev | grep wlan | awk ‘{print $2" "$10}‘ >> $pid"_net.dat"        done        sleep 15    done
Windows

The bat command is not familiar and does not know how to implement Linux inversion semantics under Windows, which is implemented in Java code.

    Import java.io.*;     /** * Created by Xuemeng Wang on 14-9-15. * API Level > */public class Getnetinfo {public static void main (string[] args) {String            uidstring = ExecCmd ("adb shell ls/proc/uid_stat");            string[] Uidarray = uidstring.split ("\ n");            int length = uidarray.length-1; for (int i=0;i<=length-1;i++) {String CONTENTRCV = execcmd ("adb shell cat/proc/uid_stat/" +ui                darray[i]+ "/TCP_RCV");                String contentsnd = execcmd ("adb shell cat/proc/uid_stat/" +uidarray[i]+ "/tcp_snd");                System.out.println (System.getproperty ("User.dir"));                    try {File File = new file (uidarray[i]+ "_recv.dat");                    if (!file.exists ()) file.createnewfile ();                    File File2 = new file (uidarray[i]+ "_snd.dat");                    if (!file2.exists ()) file2.createnewfile (); FileWriter fileWriter1 = new FilewritER (file, true);                    FileWriter fileWriter2 = new FileWriter (file2, true);                    Filewriter1.write (CONTENTRCV);                    Filewriter2.write (CONTENTSND);                    Filewriter1.close ();                Filewriter2.close ();                } catch (IOException e) {e.printstacktrace ();            }}} public static string ExecCmd (String command) {BufferedReader br = null;            StringBuffer StringBuffer = new StringBuffer ();                try {Process p = runtime.getruntime (). exec (command);                br = new BufferedReader (New InputStreamReader (P.getinputstream ()));                String line = null;                    while (line = Br.readline ()) = null) {if ("". Equals (Line.trim ())) continue;                Stringbuffer.append (line+ "\ n");          }} catch (Exception e) {e.printstacktrace ();  } finally {if (BR! = null) {try {br.close ();                    } catch (Exception e) {e.printstacktrace ();        }}} return Stringbuffer.tostring (); }    }

API level less than 16 of the situation, I did not use to, slightly off:).

Kill the process

Linux:ps -ef | grep get-android- | grep -v grep | awk ‘{print $2}‘ | xargs kill -9
Windows (running in the background is actually a CMD process, note that the following will kill all the cmd processes):

    taskkill /F /IM cmd.exe    taskkill /F /IM adb.exe
Result Collection

Using Java to analyze DAT, give the code to analyze the CPU, the project has been uploaded to Github,https://github.com/yeetrack/android-performance.

Cpuinfo.java

    Package com.meilishuo.android.performance;    Import Org.slf4j.Logger;    Import Org.slf4j.LoggerFactory;    Import Org.testng.annotations.Test;    Import java.io.*;    Import java.util.ArrayList;    Import Java.util.Iterator;    Import java.util.List;    Import Java.util.TreeMap;    /** * Created by Victor on 14-9-9.        */public class CpuInfo {private static final Logger Logger = Loggerfactory.getlogger (Meminfo.class);        private static final String Jschartpath = "target/android-info/cpu/html/";        private static final String Memfilepath = "Target/android-info/cpu/dat/cpu.dat";        treemap<string, list<string>> cpumap = new treemap<string, list<string>> (); /** * Parse Cpu.dat stored in map */public void Parsecpufile () {File File = new file (memfile            PATH);            if (null==file) return; try {bufferedreader BufferedReader = new BufferedReader (New InputStreamReader (newFileInputStream (file));                String line = null;  while ((Line=bufferedreader.readline ())!=null) {string[] array = Line.trim (). Split (""); Space-delimited if (Null==array | | array.length!=2 | |!array[0].contains ("%") | | ". Equals (Array[1]) | |"                    Name ". Equals (array[1)) continue; if (cpumap.size () ==0 | |!cpumap.containskey (ARRAY[1])) {list<string> Memli                        st = new Arraylist<string> ();                        Memlist.add (array[0].substring (0, Array[0].indexof ("%")));                    Cpumap.put (array[1], memlist); } else {cpumap.get (array[1]). Add (array[0].substring (0, array                    [0].indexof ("%")));            }} System.out.println (Cpumap.size ()); } catch (FileNotFoundException e) {E.printStackTrace ();            } catch (IOException e) {e.printstacktrace (); }}/** * writes data from map to XML */public void Writexmlfrommap () {if (null= =cpumap | |            Cpumap.size () ==0) return;            Iterator<string> it = Cpumap.keyset (). Iterator ();                while (It.hasnext ()) {String key = It.next ();                list<string> value = Cpumap.get (key);                if (Null==value | | value.size () <=1) continue;                Write XML file = new file (Jschartpath+key.replace ("/", "_"). Replace (":", "_") + "_cpu.xml"); try {bufferedwriter bufferedwriter = new BufferedWriter (new OutputStreamWriter (New FileOutputStream                    (file, True)); Bufferedwriter.write ("<?xml version=\" 1.0\ "? >\n" + "<jschart>\n                   " +         "\t<dataset type=\" line\ ">");                    int pos = 1; for (String index:value) {bufferedwriter.write ("<data unit=\" "+pos+" \ "Valu                        E=\ "+index+" \ "/>\n");                    pos++; } bufferedwriter.write ("</dataset>\n" + "\t<opt                            ionset>\n "+" \t\t<option set=\ "setlinecolor\" value=\ "' #8D9386 ' \"/>\n "+ "\t\t<option set=\" setlinewidth\ "value=\" 4\ "/>\n" + "\t\t<option set=\ "Settitlecolor\" value=\ "' #7D7D7D ' \"/>\n "+" \t\t<option set=\ "setaxiscolor\" value=\ "' #9                            F0505 ' \ "/>\n" + "\t\t<option set=\" setgridcolor\ "value=\" ' #a4a4a4 ' \ "/>\n" +       "\t\t<option set=\" setaxisvaluescolor\ "value=\" ' #333639 ' \ "/>\n" +                     "\t\t<option set=\" setaxisnamecolor\ "value=\" ' #333639 ' \ "/>\n" + "\ T                            \t<option set=\ "settextpaddingleft\" value=\ "0\"/>\n "+" \t</optionset>\n "+                    "</JSChart>");                    Bufferedwriter.flush ();                Bufferedwriter.close ();                } catch (FileNotFoundException e) {e.printstacktrace ();                } catch (IOException e) {e.printstacktrace ();            }}}/** * Generate jschart HTML file */public void writejshtml () {            File File = new file (Jschartpath); file[] Xmlfiles = file.listfiles (new FileFilter () {@Override public boolean accept (file Pat                Hname) {return pathname.getname (). EndsWith ("_cpu.xml");            }            }); if (null== xmlfiles | | xmlfiles.length==0) return; for (file index:xmlfiles) {file Htmlfile = new File (Index.getabsolutepath (). Replace (". xml", ".                HTML ")); try {bufferedwriter bufferedwriter = new BufferedWriter (new FileWriter (Htmlfile));

Continue reading,

Android Automation Performance Collection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.