Using Ddmlib for Android performance monitoring

Source: Internet
Author: User

Using Ddmlib to achieve Android performance monitoring principle: CPU

adb shell Dumpsys cpuinfo packagename

Memory

adb shell Dumpsys meminfo packagename

Flow

Cat/proc/uid_stat/uidxxx/tcp_rcv
Cat/proc/uid_stat/uidxxx/tcp_snd
Where the UID is obtained through
ADB Shell Dumpsys Package PackageName
Get Userid= (\d+) \s

FPS refresh rate

This calculation is slightly more complex, please refer to the source code:

Sdk/sources/android-18/com/android/uiautomator/platform/surfaceflingerhelper.java (Take the path in android-18 as an example, this file is also available in other versions , may be different paths)

I wrote a GUI.

Please contact [email protected], trial ~

Core Code Implementation Controller
public class Adbcontroller {protected static Logger Logger = Loggerfactory.getlogger (Adbcontroller.class);    protected static Androiddebugbridge adb = null;    private static Boolean isinit = false;    Public Adbcontroller () {init ();            } public void Init () {if (!isinit) {androiddebugbridge.init (true);           Ddmpreferences.settimeout (20000);    adb = Androiddebugbridge.createbridge ();            In this way, adb = Androiddebugbridge.createbridge (Configurationsettings.adb_path, false) will not be found when ADB is not started;        Isinit = true;    } waitdevicelist (ADB);        } private void Waitdevicelist (Androiddebugbridge bridge) {int count = 0;                while (bridge.hasinitialdevicelist () = = False) {try {thread.sleep (100);            count++; } catch (Interruptedexception e) {} if (Count >) {System.out.println ("Fail to Init Devic            E list "); Break        }}}public void Terminate () {if (devicetimer!= null) {Devicetimer.clearservice ();    } if (Devicelistener!=null) Androiddebugbridge.removedevicechangelistener (Devicelistener); Androiddebugbridge.terminate ();} Public idevice[] GetDevices () {return adb.getdevices ();} Public IDevice Getcurrentdevice () {return devicelistener.mcurrentdevice;}    Public IDevice GetDevice (String serialnum) {idevice[] devices = adb.getdevices ();    int nums = Devices.length;        for (int i = 0; i < nums; i++) {String curserialnum = Devices[i].getserialnumber ();    if (Serialnum.equals (curserialnum)) return devices[i]; } return null; public string getcurrentactivity (string monitorpackage) {sfactivityservice SF = new Sfactivityservice (getcurrentdevice    (), monitorpackage);    Sf.executecmd (); return sf.getcuractivity ();}}
Cpu
/** * Use Dumpsys cpuinfo xxx.package.name to get CPU performance metrics * @author ZEJUN.LZJ * */public class Cpuinfoservice extends Observabl E implements Adbshellservice {protected IDevice device;private cpuinforeceiver receiver = null;protected String monitorpa    Ckage;public Cpuinfoservice (IDevice device,string monitorpackage) {this.device = device;    This.monitorpackage = Monitorpackage;           Receiver = new Cpuinforeceiver ();    }public float Getcpuratio () {Float cpuratio = Receiver.getcpuratio ();    if (Cpuratio = = NULL | | Cpuratio <0) cpuratio = -1f; return cpuratio;}    public void Executecmd () {if (Stringutils.isempty (monitorpackage)) return;    String cmd = "Dumpsys cpuinfo" + monitorpackage;    try {device.executeshellcommand (cmd, receiver);        } catch (TimeoutException e) {logger.error (Log_tag, "timeoutexception");    E.printstacktrace ();    } catch (Adbcommandrejectedexception e) {logger.error (Log_tag, "adbcommandrejectedexception");    E.printstacktrace ();        } catch (Shellcommandunresponsiveexception e) {logger.error (Log_tag, "shellcommandunresponsiveexception");    E.printstacktrace ();        } catch (IOException e) {logger.error (Log_tag, "IOException");    E.printstacktrace ();    } Float ratio = Getcpuratio ();        if (ratio >=0.0) {setchanged ();    Notifyobservers (ratio);             }}public void Stop () {Receiver.setcanceledflag (true);    }private class Cpuinforeceiver extends Multilinereceiver {private Pattern cpuinfo_matcher;    Private Float mcpuratio = null;    Protected Boolean isCanceled = false;        Public Cpuinforeceiver () {super ();    Cpuinfo_matcher = Pattern.compile (". *" + monitorpackage);    The public void Setcanceledflag (Boolean isCanceled) {this.iscanceled = isCanceled;    } public Float Getcpuratio () {return mcpuratio;    } public boolean iscancelled () {return isCanceled; } @Override public void processnEwlines (string[] lines) {for (String line:lines) {Matcher Cpumatch = Cpuinfo_matcher.matcher (line); if (Cpumatch.find ()) {try {mcpuratio = Float.parsefloat (Cpumatch.group ()). SP                    Lit ("%") [0].trim ());                Break } catch (NumberFormatException e) {System.out.println (String.Format ("Failed to parse%s as an integer"                , Cpumatch.group (1))); }}}}}public void Clear () {}}
Memory
public class Meminfoservice extends Observable implements Adbshellservice {protected IDevice device;private meminforecei Ver receiver = new Meminforeceiver ();p rotected String monitorpackage;public meminfoservice (IDevice device,string    Monitorpackage) {this.device = device;    This.monitorpackage = Monitorpackage; This.addobserver (Datamanager.getinstance (). Getmemobserver ());}    /** * Get memory data from receive * @return */public float getmeminfo () {Float meminfo = Receiver.getmeminfo ();    if (Meminfo = = NULL | | Meminfo <0) meminfo = -1f; return meminfo/1000;}    Public Float Getdalvinfo () {Float dalvinfo = Receiver.getdalvinfo ();    if (Dalvinfo = = NULL | | dalvinfo <0) dalvinfo =-1f; return dalvinfo/1000;}    Public Float Getnativeinfo () {Float nativeinfo = Receiver.getnativeinfo ();    if (Nativeinfo = = NULL | | Nativeinfo < 0) Nativeinfo = -1f; return nativeinfo/1000;} public void Executecmd () {if (Stringutils.isempty (monitorpackage)) retUrn    String cmd = "Dumpsys meminfo" + monitorpackage;    try {device.executeshellcommand (cmd, receiver);        } catch (TimeoutException e) {logger.error (Log_tag, "timeoutexception");    E.printstacktrace ();        } catch (Adbcommandrejectedexception e) {logger.error (Log_tag, "adbcommandrejectedexception");    E.printstacktrace ();        } catch (Shellcommandunresponsiveexception e) {logger.error (Log_tag, "shellcommandunresponsiveexception");    E.printstacktrace ();        } catch (IOException e) {logger.error (Log_tag, "IOException");    E.printstacktrace ();    } Float Ratio1 = Getmeminfo ();    Float Ratio2 = Getdalvinfo ();    Float Ratio3 = Getnativeinfo ();        if (ratio1>0 && ratio2>0 && Ratio3 >0) {setchanged ();    Notifyobservers (New Datamanager.mem_data (Ratio1,ratio2,ratio3));    }}private static final class Meminforeceiver extends Multilinereceiver {protected Boolean isCanceled = false; PublicMeminforeceiver () {super ();    The public void Setcanceledflag (Boolean isCanceled) {this.iscanceled = isCanceled;    } public Float Getmeminfo () {return meminfo;    } public Float Getdalvinfo () {return dalvinfo;    } public Float Getnativeinfo () {return nativeinfo;    } private static final String Dalvik_matcher = "DALVIK";    private static final String Native_matcher = "NATIVE";    private static final String Total_matcher = "Total";    protected Float meminfo = null;    protected Float dalvinfo = null;    protected Float nativeinfo = null;    public boolean iscancelled () {return isCanceled;    } private list<string> tem = new arraylist<string> (); @Override public void Processnewlines (string[] lines) {for (String line:lines) {//to cache the output data tem.add            (line);                if (Line.contains (Total_matcher)) {getmeminfo (TEM);            Tem.clear (); }        }    }   public void Getmeminfo (list<string> lines) {//Arrnative[index used here], index will be different because of different version output information, some called Dalvik, have Called Dalvik Heap for (String line:lines) {if (Line.contains (Native_matcher)) {string[] ar                Rnative = Line.split ("\\s+");                if (9 = = arrnative.length) {nativeinfo = Float.parsefloat (arrnative[7]);                } else if (8 = = arrnative.length) {nativeinfo = Float.parsefloat (arrnative[6]); } else if (7 = = arrnative.length) {nativeinfo = Float.parsefloat (arrnative[5                ]);            } continue;                } if (Line.contains (Dalvik_matcher)) {string[] Arrdalvik = Line.split ("\\s+");                if (9 = = arrdalvik.length) {dalvinfo = Float.parsefloat (arrdalvik[7]); } else if (8 = = arrdalvik.length) {dalvinfo = Float.parsefLoat (Arrdalvik[6]);                } else if (7 = = arrdalvik.length) {dalvinfo = Float.parsefloat (arrdalvik[5]);            } continue;                } if (Line.contains (Total_matcher)) {String arrtotal[] = Line.split ("\\s+");                if (8 = = arrtotal.length) {meminfo = Float.parsefloat (arrtotal[6]);                }else if (7 = = arrtotal.length) {meminfo = Float.parsefloat (arrtotal[5]);            } break;             }}}}public void Stop () {Receiver.setcanceledflag (true);    }public void Clear () {}}
Fps
/** * Dumpsys Surfaceflinger--latency */public class Sflatencyservice extends Observable implements adbshellservice{    private static String Frame_latency_cmd = "Dumpsys surfaceflinger--latency";    protected IDevice device;    Private String monitorpackage; Private String windowname;protected Logger Logger = Loggerfactory.getlogger (This.getclass ());p rivate static final String Log_tag = "[sflatencyservice]-";p ublic sflatencyservice (IDevice device,string monitorpackage) {this.device = de    Vice    This.monitorpackage = Monitorpackage;    Clearsfbuffer ();    Receiver = new Latencyreceiver (this); This.addobserver (Datamanager.getinstance (). Getfpsobserver ());} Private Latencyreceiver receiver = null;private float laterfps;public float getlaterfps () {return laterfps;}    public void Setlaterfps (Float laterfps) {this.laterfps = Laterfps;        if (laterfps>0) {setchanged ();    Notifyobservers (New Datamanager.fps_data (Windowname,laterfps)); }}public String GetactiviTy () {sfactivityservice SF = new Sfactivityservice (device,monitorpackage);    Sf.executecmd (); return sf.getcuractivity ();}    public void Clearsfbuffer () {Sfclearservice sc = new Sfclearservice (device); Sc.executecmd ();}    public void Executecmd () {if (Stringutils.isempty (monitorpackage)) return;    Windowname = Getactivity ();    String command = Frame_latency_cmd;    Command = String.Format ("%s%s", Frame_latency_cmd, Windowname);    try {device.executeshellcommand (command,receiver);        } catch (TimeoutException e) {logger.error (Log_tag, "timeoutexception");    E.printstacktrace ();        } catch (Adbcommandrejectedexception e) {logger.error (Log_tag, "adbcommandrejectedexception");    E.printstacktrace ();        } catch (Shellcommandunresponsiveexception e) {logger.error (Log_tag, "shellcommandunresponsiveexception");    E.printstacktrace ();        } catch (IOException e) {logger.error (Log_tag, "IOException"); E.printstacktrace(); }}public void Stop () {}private static final class Latencyreceiver extends Multilinereceiver {sflatencyservice par    Ent    Public Latencyreceiver (sflatencyservice parent) {this.parent = parent;    } protected Float fps = 0f;    private static int buffer_size = 128;    private static int buffer_number = 3; /* An array list which includes the raw buffer information from frame latency tool */private static list<list<st    ring>> mframebufferdata = new arraylist<list<string>> (buffer_size);    /* Record The Refresh period returned from driver *///private static Long mrefreshperiod =-1; Symbol of unfinished frame time */public static final String pending_fence_time = new Long (long.max_value). toString    ();    private static final Pattern Check_matcher = Pattern.compile ("^[\\d\\s]+$");    public boolean iscancelled () {return false;    } public void Clearbuffer () {mframebufferdata.clear (); } @Override PUBlic void Processnewlines (string[] lines) {if (lines.length<2) return;            for (String line:lines) {Matcher Matcher = Check_matcher.matcher (line);            if (!matcher.matches ()) continue;            string[] buffervalues = Line.split ("\\s+");                if (buffervalues.length==1) {if (Line.trim (). IsEmpty ()) continue;                    if (Mframebufferdata.isempty ()) {//mrefreshperiod = Long.parselong (Line.trim ());                Continue                    } else {fps = (float) getframerate ();                    Parent.setlaterfps (fps);                    Mrefreshperiod = Long.parselong (Line.trim ());                    Clearbuffer ();                Continue            }} if (Buffervalues.length!=buffer_number) return;            if (Buffervalues[0].trim (). CompareTo ("0") = = 0) {continue; } else if (BuffervaluEs[1].trim (). CompareTo (pending_fence_time) = = 0) {System.out.println (Log_tag + "The data contains Unfinis                Hed frame Time ");            Continue            } list<string> Delayarray = Arrays.aslist (buffervalues);                       Mframebufferdata.add (Delayarray); }}/** * Calculate frame rate * @return */public static double Getframerate () {int Mframel        Atencysamplesize = Mframebufferdata.size ()-1;        Long startTime = Long.parselong (mframebufferdata.get (0). Get (1));        Long endTime = Long.parselong (Mframebufferdata.get (mframelatencysamplesize). Get (1));        Long totalduration = Endtime-starttime;    Return (double) ((mFrameLatencySampleSize-1) * MATH.POW (Ten, 9))/totalduration; }}public void Clear () {if (receiver!=null) Receiver.clearbuffer ();}}
Flow
public class Trafficinfoservice extends Observable implements Adbshellservice {protected IDevice device;protected String UID = null;private trafficreceiver receiver;private String monitorpackage;integer RCV = Null;integer snd = Null;Integer fl ow = null;private static integer FIRSTRCV = null;private static integer firstsnd = null;public integer GETRCV () {retur n Rcv;} Public Integer getsnd () {return snd;} Public Integer Getflow () {return flow;}    Public Trafficinfoservice (IDevice device, String monitorpackage) {this.device = device;    Receiver = new Trafficreceiver ();    This.monitorpackage = Monitorpackage; This.addobserver (Datamanager.getinstance (). Getflowobserver ());}    Protected String Getuid () {Uidservice service = new Uidservice (device,monitorpackage);    Service.executecmd (); return Service.getuid ();}    public void Executecmd () {if (Stringutils.isempty (monitorpackage)) return;    if (uid = = null) UID = Getuid (); String cmd = String.Format ("Cat/prOc/uid_stat/%s/tcp_rcv;cat/proc/uid_stat/%s/tcp_snd ", uid,uid);    try {device.executeshellcommand (cmd, receiver);        } catch (TimeoutException e) {logger.error (Log_tag, "timeoutexception");    E.printstacktrace ();        } catch (Adbcommandrejectedexception e) {logger.error (Log_tag, "adbcommandrejectedexception");    E.printstacktrace ();        } catch (Shellcommandunresponsiveexception e) {logger.error (Log_tag, "shellcommandunresponsiveexception");    E.printstacktrace ();        } catch (IOException e) {logger.error (Log_tag, "IOException");    E.printstacktrace (); } notifydata ();}    public void Notifydata () {RCV = RECEIVER.GETRCV ();    SND = Receiver.getsnd ();    if (Rcv <0 | | snd<0) return;    if (FIRSTRCV = = null) FIRSTRCV = RCV;    if (firstsnd = = null) firstsnd = SND;    RCV = RCV-FIRSTRCV;    SND = snd-firstsnd;    Flow = Rcv + snd;    Setchanged (); Notifyobservers (New Datamanager.flow_data (FLOW,SND,RCV));} Public VOID Stop () {Receiver.setcanceledflag (true);    FIRSTRCV = null; firstsnd = null;}    Private static final class Trafficreceiver extends Multilinereceiver {private Integer MRCV = null;    Private Integer msnd = null;    Protected Boolean isCanceled = false;    public void Setcanceledflag (Boolean isCanceled) {this.iscanceled = isCanceled;        } public Integer Getrcv () {if (MRCV = = NULL | | MRCV <0) MRCV =-1;    return MRCV;        } public Integer getsnd () {if (msnd = = NULL | | msnd <0) msnd =-1;    return msnd;    } public boolean iscancelled () {return isCanceled;        } @Override public void Processnewlines (string[] lines) {//system.out.println (lines[0]);        if (lines.length<2) return;            try{MRCV = Integer.parseint (Lines[0].trim ())/1000;        msnd = Integer.parseint (Lines[1].trim ())/1000; } catch (NumberFormatException e) {System.out.println (Log_tag + String.Format (": Failed to parse%s to traffic", lines[0]+lines[1]));    }}}public void Clear () {FIRSTRCV = null;    firstsnd = null;}}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Using Ddmlib for Android performance monitoring

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.