<div id="article_content" class="article_content tracking-ad" data-mod="popu_307" data-dsm="post">

<p>本人在使用UiAutomator做自动化测试的时候,需要对对手机在运行用例或者执行monkey期间的cpu和内存使用情况做统计。想了一个方案,使用多线程,执行adb shell top命令,然后处理得到的信息,写入数据库中。经过尝试终于成功了,效果还不错,分享出来,供大家参考。</p>
<p>下图为数据库中的数据。</p>
<p><img src="" alt=""><br>
</p>
<p>备注:代码里包含了使用adb shell dumpsys获取信息的方法,不过在dumpsys cpuinfo的时候遇到一些问题,统计的是一个很长的时间段的,后来就放弃了这种方法,重新写了getCpuAndMemDate()方法。</p>
<p>明天来了补上注释。(已补)</p>
<p>下面是统计信息和存入数据库的类。</p>
<p></p>
<div class="dp-highlighter bg_java"><div class="bar"><div class="tools"><b>[java]</b> <a href="#" class="ViewSource" title="view plain" οnclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" target="_blank">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" οnclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" target="_blank">copy</a><div style="position: absolute; left: 485px; top: 970px; width: 18px; height: 18px; z-index: 99;"><embed id="ZeroClipboardMovie_1" src="" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="18" height="18" name="ZeroClipboardMovie_1" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=1&width=18&height=18" wmode="transparent"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" οnclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" target="_blank">print</a></span><a href="#" class="About" title="?" οnclick="dp.sh.Toolbar.Command('About',this);return false;" target="_blank">?</a></div></div><ol start="1" class="dp-j"><li class="alt"><span><span class="keyword">package</span><span> source;  </span></span></li><li class=""><span>  </span></li><li class="alt"><span><span class="keyword">import</span><span> java.io.BufferedReader;  </span></span></li><li class=""><span><span class="keyword">import</span><span> java.io.IOException;  </span></span></li><li class="alt"><span><span class="keyword">import</span><span> java.io.InputStream;  </span></span></li><li class=""><span><span class="keyword">import</span><span> java.io.InputStreamReader;  </span></span></li><li class="alt"><span><span class="keyword">import</span><span> java.sql.SQLException;  </span></span></li><li class=""><span><span class="keyword">import</span><span> java.util.regex.Matcher;  </span></span></li><li class="alt"><span><span class="keyword">import</span><span> java.util.regex.Pattern;  </span></span></li><li class=""><span><span class="comment">/**</span> </span></li><li class="alt"><span><span class="comment">* @author ··-·尘</span> </span></li><li class=""><span><span class="comment">* @E-mail:Fhaohaizi@163.com</span> </span></li><li class="alt"><span><span class="comment">* @version 创建时间:2017年8月23日 下午2:56:22</span> </span></li><li class=""><span><span class="comment">* @alter 修改时间:2017年8月24日 10:02:19</span> </span></li><li class="alt"><span><span class="comment">* 类说明:测试内存和cpu信息</span> </span></li><li class=""><span><span class="comment">*/</span><span>  </span></span></li><li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">class</span><span> PerformanceTest </span><span class="keyword">extends</span><span> Thread{  </span></span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">static</span><span> </span><span class="keyword">boolean</span><span> key = </span><span class="keyword">true</span><span>;  </span></span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">int</span><span> test_mark = (</span><span class="keyword">int</span><span>) (System.currentTimeMillis()/</span><span class="number">1000</span><span>);  </span></span></li><li class=""><span>    <span class="comment">//创建实例</span><span>  </span></span></li><li class="alt"><span>    <span class="keyword">private</span><span> </span><span class="keyword">static</span><span> PerformanceTest performanceTest = </span><span class="keyword">new</span><span> PerformanceTest();  </span></span></li><li class=""><span>    <span class="comment">//公共访问方法</span><span>  </span></span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">static</span><span> PerformanceTest getInstance() {  </span></span></li><li class=""><span>        <span class="keyword">return</span><span> performanceTest;  </span></span></li><li class="alt"><span>    }  </span></li><li class=""><span>    <span class="comment">//私有构造方法</span><span>  </span></span></li><li class="alt"><span>    <span class="keyword">private</span><span> PerformanceTest() {  </span></span></li><li class=""><span>        output(<span class="string">"欢迎使用手机性能监控线程!"</span><span>);  </span></span></li><li class="alt"><span>    }  </span></li><li class=""><span>    <span class="comment">//用于调试监控方法,可删除</span><span>  </span></span></li><li class="alt"><span><span class="comment">//  public static void main(String[] args) throws SQLException {</span><span>  </span></span></li><li class=""><span><span class="comment">//      PerformanceTest.getInstance().getCpuAndMemDate();</span><span>  </span></span></li><li class="alt"><span><span class="comment">//  }</span><span>  </span></span></li><li class=""><span>    <span class="comment">//重写run方法</span><span>  </span></span></li><li class="alt"><span>    <span class="annotation">@Override</span><span>  </span></span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> run() {  </span></span></li><li class="alt"><span>        <span class="keyword">while</span><span>(key) {</span><span class="comment">//循环执行该方法</span><span>  </span></span></li><li class=""><span>            <span class="keyword">try</span><span> {  </span></span></li><li class="alt"><span>                sleep(<span class="number">15</span><span> * </span><span class="number">1000</span><span>);</span><span class="comment">//线程休眠</span><span>  </span></span></li><li class=""><span>                } <span class="keyword">catch</span><span> (InterruptedException e1) {  </span></span></li><li class="alt"><span>                    e1.printStackTrace();<span class="comment">//打印异常</span><span>  </span></span></li><li class=""><span>                    }  </span></li><li class="alt"><span>            <span class="keyword">try</span><span> {  </span></span></li><li class=""><span><span class="comment">//              getCpuAndMemResult();//该方法由于dumpsys数据不准确暂时放弃</span><span>  </span></span></li><li class="alt"><span>                getCpuAndMemDate();<span class="comment">//执行监控方法</span><span>  </span></span></li><li class=""><span>                } <span class="keyword">catch</span><span> (SQLException e) {  </span></span></li><li class="alt"><span>                    e.printStackTrace();<span class="comment">//打印异常</span><span>  </span></span></li><li class=""><span>                    }  </span></li><li class="alt"><span>            }  </span></li><li class=""><span>        }  </span></li><li class="alt"><span>    <span class="comment">//获取cpu和mem数据</span><span>  </span></span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> getCpuAndMemDate() </span><span class="keyword">throws</span><span> SQLException {  </span></span></li><li class="alt"><span><span style=<span class="string">"white-space:pre"</span><span>>      </span></span><span class="keyword">int</span><span>[] result = getPerformanceResult();</span><span class="comment">//获取数据</span><span>  </span></span></li><li class=""><span><span style=<span class="string">"white-space:pre"</span><span>>      </span></span><span class="keyword">int</span><span> cpu_result = result[</span><span class="number">0</span><span>];</span><span class="comment">//获取cpu</span><span>  </span></span></li><li class="alt"><span><span style=<span class="string">"white-space:pre"</span><span>>      </span></span><span class="keyword">int</span><span> vss = result[</span><span class="number">1</span><span>];</span><span class="comment">//获取虚拟内存数据</span><span>  </span></span></li><li class=""><span><span style=<span class="string">"white-space:pre"</span><span>>      </span></span><span class="keyword">int</span><span> rss = result[</span><span class="number">2</span><span>];</span><span class="comment">//获取物理内存数据</span><span>  </span></span></li><li class="alt"><span>        AppLocalMySql.getInstance().saveMemAndCpuResult(test_mark, cpu_result, vss, rss);<span class="comment">//写入数据库</span><span>  </span></span></li><li class=""><span>    }  </span></li><li class="alt"><span>    <span class="comment">//获取cpu和mem数据</span><span>  </span></span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> getCpuAndMemResult() </span><span class="keyword">throws</span><span> SQLException {  </span></span></li><li class="alt"><span>        <span class="keyword">double</span><span> cpu_result = getCpuResult();</span><span class="comment">//获取cpu数据</span><span>  </span></span></li><li class=""><span>        <span class="keyword">int</span><span> mem_result = getMemResult();</span><span class="comment">//获取内存数据</span><span>  </span></span></li><li class="alt"><span>        AppLocalMySql.getInstance().saveMemAndCpuResult(test_mark, cpu_result, mem_result);<span class="comment">//写入数据库</span><span>  </span></span></li><li class=""><span>        }  </span></li><li class="alt"><span>    <span class="comment">//获取统计结果</span><span>  </span></span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">int</span><span>[] getPerformanceResult() {  </span></span></li><li class="alt"><span>        String cmd = <span class="string">"adb shell top -m 10 -n 1"</span><span>;</span><span class="comment">//执行adb命令-m表示条数,-n循环获取次数,此处写为1</span><span>  </span></span></li><li class=""><span>        <span class="comment">//初始化</span><span>  </span></span></li><li class="alt"><span>        <span class="keyword">int</span><span> cpu_result = </span><span class="number">0</span><span>;  </span></span></li><li class=""><span>        <span class="keyword">int</span><span> vss = </span><span class="number">0</span><span>;  </span></span></li><li class="alt"><span>        <span class="keyword">int</span><span> rss = </span><span class="number">0</span><span>;  </span></span></li><li class=""><span>        <span class="keyword">try</span><span> {  </span></span></li><li class="alt"><span>            Process p = Runtime.getRuntime().exec(cmd);<span class="comment">//通过runtime类执行cmd命令</span><span>  </span></span></li><li class=""><span>            <span class="comment">// 正确输出流</span><span>  </span></span></li><li class="alt"><span>            InputStream input = p.getInputStream();<span class="comment">//创建并实例化输入字节流</span><span>  </span></span></li><li class=""><span>            BufferedReader reader = <span class="keyword">new</span><span> BufferedReader(</span><span class="keyword">new</span><span> InputStreamReader(input));</span><span class="comment">//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容</span><span>  </span></span></li><li class="alt"><span>            String line = <span class="string">""</span><span>;  </span></span></li><li class=""><span>            <span class="keyword">while</span><span> ((line = reader.readLine()) != </span><span class="keyword">null</span><span>) {</span><span class="comment">//循环读取</span><span>  </span></span></li><li class="alt"><span>                <span class="keyword">if</span><span> (line.contains(</span><span class="string">"com.gaotu100.superclass"</span><span>)) {</span><span class="comment">//获取行</span><span>  </span></span></li><li class=""><span><span class="comment">//                  output(line);//输出行</span><span>  </span></span></li><li class="alt"><span>                    <span class="comment">//获取数据</span><span>  </span></span></li><li class=""><span>                    cpu_result = getCpuDate(line);  </span></li><li class="alt"><span>                    vss = getVss(line);  </span></li><li class=""><span>                    rss = getRss(line);  </span></li><li class="alt"><span>                    }  </span></li><li class=""><span>                }  </span></li><li class="alt"><span>            reader.close();<span class="comment">//此处reader依赖于input,应先关闭</span><span>  </span></span></li><li class=""><span>            input.close();<span class="comment">//关闭流</span><span>  </span></span></li><li class="alt"><span>            <span class="comment">// 错误输出流</span><span>  </span></span></li><li class=""><span>            InputStream errorInput = p.getErrorStream();<span class="comment">//创建并实例化输入字节流</span><span>  </span></span></li><li class="alt"><span>            BufferedReader errorReader = <span class="keyword">new</span><span> BufferedReader(</span><span class="keyword">new</span><span> InputStreamReader(errorInput));</span><span class="comment">//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容</span><span>  </span></span></li><li class=""><span>            String eline = <span class="string">""</span><span>;  </span></span></li><li class="alt"><span>            <span class="keyword">while</span><span> ((eline = errorReader.readLine()) != </span><span class="keyword">null</span><span>) {</span><span class="comment">//循环读取</span><span>  </span></span></li><li class=""><span>                System.out.println(eline);<span class="comment">//输出</span><span>  </span></span></li><li class="alt"><span>                }  </span></li><li class=""><span>            errorReader.close();<span class="comment">//此处有依赖关系,先关闭errorReader</span><span>  </span></span></li><li class="alt"><span>            errorInput.close();<span class="comment">//关闭流</span><span>  </span></span></li><li class=""><span>            } <span class="keyword">catch</span><span> (IOException e) {  </span></span></li><li class="alt"><span>                output(<span class="string">"执行"</span><span> + cmd + </span><span class="string">"失败!"</span><span>);  </span></span></li><li class=""><span>                e.printStackTrace();  </span></li><li class="alt"><span>                }  </span></li><li class=""><span>        <span class="keyword">int</span><span>[] result = {cpu_result, vss, rss};</span><span class="comment">//新建数组保存数据</span><span>  </span></span></li><li class="alt"><span>        <span class="keyword">return</span><span> result;</span><span class="comment">//返回数组</span><span>  </span></span></li><li class=""><span>    }  </span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">int</span><span> getMemResult() {  </span></span></li><li class=""><span>        String cmd1 = <span class="string">"adb shell dumpsys meminfo com.gaotu100.superclass"</span><span>;  </span></span></li><li class="alt"><span>        <span class="keyword">int</span><span> mem_result = </span><span class="number">0</span><span>;  </span></span></li><li class=""><span>        <span class="keyword">try</span><span> {  </span></span></li><li class="alt"><span>            Process p = Runtime.getRuntime().exec(cmd1);<span class="comment">//通过runtime类执行cmd命令</span><span>  </span></span></li><li class=""><span>            <span class="comment">// 正确输出流</span><span>  </span></span></li><li class="alt"><span>            InputStream input = p.getInputStream();<span class="comment">//创建并实例化输入字节流</span><span>  </span></span></li><li class=""><span>            BufferedReader reader = <span class="keyword">new</span><span> BufferedReader(</span><span class="keyword">new</span><span> InputStreamReader(input));</span><span class="comment">//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容</span><span>  </span></span></li><li class="alt"><span>            String line = <span class="string">""</span><span>;  </span></span></li><li class=""><span>            <span class="keyword">while</span><span> ((line = reader.readLine()) != </span><span class="keyword">null</span><span>) {</span><span class="comment">//循环读取</span><span>  </span></span></li><li class="alt"><span>                <span class="keyword">if</span><span> (line.startsWith(</span><span class="string">"        TOTAL"</span><span>)) {  </span></span></li><li class=""><span>                    mem_result = getMemInfo(line);  </span></li><li class="alt"><span>                }  </span></li><li class=""><span>                    }  </span></li><li class="alt"><span>            reader.close();<span class="comment">//此处reader依赖于input,应先关闭</span><span>  </span></span></li><li class=""><span>            input.close();  </span></li><li class="alt"><span>            <span class="comment">// 错误输出流</span><span>  </span></span></li><li class=""><span>            InputStream errorInput = p.getErrorStream();<span class="comment">//创建并实例化输入字节流</span><span>  </span></span></li><li class="alt"><span>            BufferedReader errorReader = <span class="keyword">new</span><span> BufferedReader(</span><span class="keyword">new</span><span> InputStreamReader(errorInput));</span><span class="comment">//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容</span><span>  </span></span></li><li class=""><span>            String eline = <span class="string">""</span><span>;  </span></span></li><li class="alt"><span>            <span class="keyword">while</span><span> ((eline = errorReader.readLine()) != </span><span class="keyword">null</span><span>) {</span><span class="comment">//循环读取</span><span>  </span></span></li><li class=""><span>                System.out.println(eline);<span class="comment">//输出</span><span>  </span></span></li><li class="alt"><span>                }  </span></li><li class=""><span>            errorReader.close();<span class="comment">//此处有依赖关系,先关闭errorReader</span><span>  </span></span></li><li class="alt"><span>            errorInput.close();  </span></li><li class=""><span>            } <span class="keyword">catch</span><span> (IOException e) {  </span></span></li><li class="alt"><span>                output(<span class="string">"执行"</span><span> + cmd1 + </span><span class="string">"失败!"</span><span>);  </span></span></li><li class=""><span>                e.printStackTrace();  </span></li><li class="alt"><span>                }  </span></li><li class=""><span>        <span class="keyword">return</span><span> mem_result;  </span></span></li><li class="alt"><span>        }  </span></li><li class=""><span>      </span></li><li class="alt"><span>    <span class="comment">//获取cpu统计结果</span><span>  </span></span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">double</span><span> getCpuResult() {  </span></span></li><li class="alt"><span>        String cmd = <span class="string">"adb shell dumpsys cpuinfo"</span><span>;  </span></span></li><li class=""><span>        <span class="keyword">double</span><span> cpu_result = </span><span class="number">0.0</span><span>;  </span></span></li><li class="alt"><span>        <span class="keyword">try</span><span> {  </span></span></li><li class=""><span>            Process p = Runtime.getRuntime().exec(cmd);<span class="comment">//通过runtime类执行cmd命令</span><span>  </span></span></li><li class="alt"><span>            <span class="comment">// 正确输出流</span><span>  </span></span></li><li class=""><span>            InputStream input = p.getInputStream();<span class="comment">//创建并实例化输入字节流</span><span>  </span></span></li><li class="alt"><span>            BufferedReader reader = <span class="keyword">new</span><span> BufferedReader(</span><span class="keyword">new</span><span> InputStreamReader(input));</span><span class="comment">//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容</span><span>  </span></span></li><li class=""><span>            String line = <span class="string">""</span><span>;  </span></span></li><li class="alt"><span>            <span class="keyword">while</span><span> ((line = reader.readLine()) != </span><span class="keyword">null</span><span>) {</span><span class="comment">//循环读取</span><span>  </span></span></li><li class=""><span>                <span class="keyword">if</span><span> (line.contains(</span><span class="string">"com.gaotu100.superclass"</span><span>)) {  </span></span></li><li class="alt"><span>                    cpu_result += getCpuInfo(line);  </span></li><li class=""><span>                    }  </span></li><li class="alt"><span>                }  </span></li><li class=""><span>            reader.close();<span class="comment">//此处reader依赖于input,应先关闭</span><span>  </span></span></li><li class="alt"><span>            input.close();  </span></li><li class=""><span>            <span class="comment">// 错误输出流</span><span>  </span></span></li><li class="alt"><span>            InputStream errorInput = p.getErrorStream();<span class="comment">//创建并实例化输入字节流</span><span>  </span></span></li><li class=""><span>            BufferedReader errorReader = <span class="keyword">new</span><span> BufferedReader(</span><span class="keyword">new</span><span> InputStreamReader(errorInput));</span><span class="comment">//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容</span><span>  </span></span></li><li class="alt"><span>            String eline = <span class="string">""</span><span>;  </span></span></li><li class=""><span>            <span class="keyword">while</span><span> ((eline = errorReader.readLine()) != </span><span class="keyword">null</span><span>) {</span><span class="comment">//循环读取</span><span>  </span></span></li><li class="alt"><span>                System.out.println(eline);<span class="comment">//输出</span><span>  </span></span></li><li class=""><span>                }  </span></li><li class="alt"><span>            errorReader.close();<span class="comment">//此处有依赖关系,先关闭errorReader</span><span>  </span></span></li><li class=""><span>            errorInput.close();  </span></li><li class="alt"><span>            } <span class="keyword">catch</span><span> (IOException e) {  </span></span></li><li class=""><span>                output(<span class="string">"执行"</span><span> + cmd + </span><span class="string">"失败!"</span><span>);  </span></span></li><li class="alt"><span>                e.printStackTrace();  </span></li><li class=""><span>                }  </span></li><li class="alt"><span>        <span class="keyword">return</span><span> cpu_result;  </span></span></li><li class=""><span>    }  </span></li><li class="alt"><span>    <span class="comment">//获取内存信息</span><span>  </span></span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">int</span><span> getMemInfo(String info) {  </span></span></li><li class="alt"><span>        <span class="keyword">int</span><span> result = </span><span class="number">0</span><span>;  </span></span></li><li class=""><span>        Pattern r = Pattern.compile(<span class="string">" [0-9]+ "</span><span>);  </span></span></li><li class="alt"><span>        Matcher m = r.matcher(info);  </span></li><li class=""><span>        <span class="keyword">if</span><span> (m.find()) {  </span></span></li><li class="alt"><span>            System.out.println(m.group());  </span></li><li class=""><span>            result = changeStringToInt(m.group().trim());  </span></li><li class="alt"><span>            }  </span></li><li class=""><span>        <span class="keyword">return</span><span> result;  </span></span></li><li class="alt"><span>        }  </span></li><li class=""><span>    <span class="comment">//获取cpu运行信息</span><span>  </span></span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">double</span><span> getCpuInfo(String info) {  </span></span></li><li class=""><span>        String percent = info.substring(<span class="number">0</span><span>, info.indexOf(</span><span class="string">"%"</span><span>));  </span></span></li><li class="alt"><span>        <span class="keyword">double</span><span> result = changeStringToDouble(percent.trim());  </span></span></li><li class=""><span>        <span class="keyword">return</span><span> result;  </span></span></li><li class="alt"><span>    }  </span></li><li class=""><span>    <span class="comment">//获取cpu运行信息</span><span>  </span></span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">int</span><span> getCpuDate(String info) {  </span></span></li><li class=""><span>        Pattern pattern = Pattern.compile(<span class="string">" [0-9]*%"</span><span>);  </span></span></li><li class="alt"><span>        Matcher matcher = pattern.matcher(info);  </span></li><li class=""><span>        <span class="keyword">if</span><span> (matcher.find()) {  </span></span></li><li class="alt"><span>            output(matcher.group());  </span></li><li class=""><span>        }  </span></li><li class="alt"><span>        String date = matcher.group().trim();  </span></li><li class=""><span>        output(date.substring(<span class="number">0</span><span>, date.length() -</span><span class="number">1</span><span> ));  </span></span></li><li class="alt"><span>        <span class="keyword">return</span><span> changeStringToInt(date.substring(</span><span class="number">0</span><span>, date.length() -</span><span class="number">1</span><span> ));  </span></span></li><li class=""><span>    }  </span></li><li class="alt"><span>      </span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">int</span><span> getVss(String info) {  </span></span></li><li class="alt"><span>        Pattern pattern = Pattern.compile(<span class="string">" [0-9]+K"</span><span>);  </span></span></li><li class=""><span>        Matcher matcher = pattern.matcher(info);  </span></li><li class="alt"><span>        <span class="keyword">if</span><span> (matcher.find()) {  </span></span></li><li class=""><span>            output(matcher.group());  </span></li><li class="alt"><span>        }  </span></li><li class=""><span>        String date = matcher.group().trim();  </span></li><li class="alt"><span><span class="comment">//      output(date.substring(0, date.length() -1));</span><span>  </span></span></li><li class=""><span>        <span class="keyword">return</span><span> changeStringToInt(date.substring(</span><span class="number">0</span><span>, date.length() -</span><span class="number">1</span><span>));  </span></span></li><li class="alt"><span>    }  </span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">int</span><span> getRss(String info) {  </span></span></li><li class="alt"><span>        Pattern pattern = Pattern.compile(<span class="string">"K +[0-9]+K"</span><span>);  </span></span></li><li class=""><span>        Matcher matcher = pattern.matcher(info);  </span></li><li class="alt"><span>        <span class="keyword">if</span><span> (matcher.find()) {  </span></span></li><li class=""><span>            output(matcher.group());  </span></li><li class="alt"><span>        }  </span></li><li class=""><span>        String date = matcher.group().substring(<span class="number">1</span><span>, matcher.group().length() - </span><span class="number">1</span><span>);  </span></span></li><li class="alt"><span><span class="comment">//      output(date.trim());</span><span>  </span></span></li><li class=""><span>        <span class="keyword">return</span><span> changeStringToInt(date.trim());  </span></span></li><li class="alt"><span>    }  </span></li><li class=""><span>      </span></li><li class="alt"><span>    <span class="comment">//把string类型转化为double</span><span>  </span></span></li><li class=""><span>    <span class="keyword">public</span><span> Double changeStringToDouble (String text) {  </span></span></li><li class="alt"><span><span class="comment">//      return Integer.parseInt(text);</span><span>  </span></span></li><li class=""><span>        <span class="keyword">return</span><span> Double.valueOf(text);  </span></span></li><li class="alt"><span>    }  </span></li><li class=""><span>    <span class="comment">//把string类型转化为int</span><span>  </span></span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">int</span><span> changeStringToInt (String text) {  </span></span></li><li class=""><span><span class="comment">//      return Integer.parseInt(text);</span><span>  </span></span></li><li class="alt"><span>        <span class="keyword">return</span><span> Integer.valueOf(text);  </span></span></li><li class=""><span>    }  </span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> output(String text) {</span><span class="comment">//明显输出</span><span>  </span></span></li><li class=""><span>        System.out.println(text);  </span></li><li class="alt"><span>    }  </span></li><li class=""><span>    <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> output(</span><span class="keyword">double</span><span> num) {</span><span class="comment">//明显输出</span><span>  </span></span></li><li class="alt"><span>        System.out.println(num);  </span></li><li class=""><span>    }  </span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> output(</span><span class="keyword">int</span><span> num) {</span><span class="comment">//方法重载</span><span>  </span></span></li><li class=""><span>        System.out.println(<span class="string">"===="</span><span>+num+</span><span class="string">"===="</span><span>);  </span></span></li><li class="alt"><span>    }     </span></li><li class=""><span>          </span></li><li class="alt"><span>    }  </span></li></ol></div><pre code_snippet_id="2547879" snippet_file_name="blog_20170824_1_7765357" name="code" class="java" style="display: none;">package source;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author ··-·尘
* @E-mail:Fhaohaizi@163.com
* @version 创建时间:2017年8月23日 下午2:56:22
* @alter 修改时间:2017年8月24日 10:02:19
* 类说明:测试内存和cpu信息
*/
public class PerformanceTest extends Thread{
	public static boolean key = true;
	public int test_mark = (int) (System.currentTimeMillis()/1000);
	//创建实例
	private static PerformanceTest performanceTest = new PerformanceTest();
	//公共访问方法
	public static PerformanceTest getInstance() {
		return performanceTest;
	}
	//私有构造方法
	private PerformanceTest() {
		output("欢迎使用手机性能监控线程!");
	}
	//用于调试监控方法,可删除
//	public static void main(String[] args) throws SQLException {
//		PerformanceTest.getInstance().getCpuAndMemDate();
//	}
	//重写run方法
	@Override
	public void run() {
		while(key) {//循环执行该方法
			try {
				sleep(15 * 1000);//线程休眠
				} catch (InterruptedException e1) {
					e1.printStackTrace();//打印异常
					}
			try {
//				getCpuAndMemResult();//该方法由于dumpsys数据不准确暂时放弃
				getCpuAndMemDate();//执行监控方法
				} catch (SQLException e) {
					e.printStackTrace();//打印异常
					}
			}
		}
	//获取cpu和mem数据
	public void getCpuAndMemDate() throws SQLException {
<span style="white-space:pre">		</span>int[] result = getPerformanceResult();//获取数据
<span style="white-space:pre">		</span>int cpu_result = result[0];//获取cpu
<span style="white-space:pre">		</span>int vss = result[1];//获取虚拟内存数据
<span style="white-space:pre">		</span>int rss = result[2];//获取物理内存数据
		AppLocalMySql.getInstance().saveMemAndCpuResult(test_mark, cpu_result, vss, rss);//写入数据库
	}
	//获取cpu和mem数据
	public void getCpuAndMemResult() throws SQLException {
		double cpu_result = getCpuResult();//获取cpu数据
		int mem_result = getMemResult();//获取内存数据
		AppLocalMySql.getInstance().saveMemAndCpuResult(test_mark, cpu_result, mem_result);//写入数据库
		}
	//获取统计结果
	public int[] getPerformanceResult() {
		String cmd = "adb shell top -m 10 -n 1";//执行adb命令-m表示条数,-n循环获取次数,此处写为1
		//初始化
		int cpu_result = 0;
		int vss = 0;
		int rss = 0;
		try {
			Process p = Runtime.getRuntime().exec(cmd);//通过runtime类执行cmd命令
			// 正确输出流
			InputStream input = p.getInputStream();//创建并实例化输入字节流
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容
			String line = "";
			while ((line = reader.readLine()) != null) {//循环读取
				if (line.contains("com.gaotu100.superclass")) {//获取行
//					output(line);//输出行
					//获取数据
					cpu_result = getCpuDate(line);
					vss = getVss(line);
					rss = getRss(line);
					}
				}
			reader.close();//此处reader依赖于input,应先关闭
			input.close();//关闭流
			// 错误输出流
			InputStream errorInput = p.getErrorStream();//创建并实例化输入字节流
			BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorInput));//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容
			String eline = "";
			while ((eline = errorReader.readLine()) != null) {//循环读取
				System.out.println(eline);//输出
				}
			errorReader.close();//此处有依赖关系,先关闭errorReader
			errorInput.close();//关闭流
			} catch (IOException e) {
				output("执行" + cmd + "失败!");
				e.printStackTrace();
				}
		int[] result = {cpu_result, vss, rss};//新建数组保存数据
		return result;//返回数组
	}
	public int getMemResult() {
		String cmd1 = "adb shell dumpsys meminfo com.gaotu100.superclass";
		int mem_result = 0;
		try {
			Process p = Runtime.getRuntime().exec(cmd1);//通过runtime类执行cmd命令
			// 正确输出流
			InputStream input = p.getInputStream();//创建并实例化输入字节流
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容
			String line = "";
			while ((line = reader.readLine()) != null) {//循环读取
				if (line.startsWith("        TOTAL")) {
					mem_result = getMemInfo(line);
				}
					}
			reader.close();//此处reader依赖于input,应先关闭
			input.close();
			// 错误输出流
			InputStream errorInput = p.getErrorStream();//创建并实例化输入字节流
			BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorInput));//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容
			String eline = "";
			while ((eline = errorReader.readLine()) != null) {//循环读取
				System.out.println(eline);//输出
				}
			errorReader.close();//此处有依赖关系,先关闭errorReader
			errorInput.close();
			} catch (IOException e) {
				output("执行" + cmd1 + "失败!");
				e.printStackTrace();
				}
		return mem_result;
		}
	
	//获取cpu统计结果
	public double getCpuResult() {
		String cmd = "adb shell dumpsys cpuinfo";
		double cpu_result = 0.0;
		try {
			Process p = Runtime.getRuntime().exec(cmd);//通过runtime类执行cmd命令
			// 正确输出流
			InputStream input = p.getInputStream();//创建并实例化输入字节流
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容
			String line = "";
			while ((line = reader.readLine()) != null) {//循环读取
				if (line.contains("com.gaotu100.superclass")) {
					cpu_result += getCpuInfo(line);
					}
				}
			reader.close();//此处reader依赖于input,应先关闭
			input.close();
			// 错误输出流
			InputStream errorInput = p.getErrorStream();//创建并实例化输入字节流
			BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorInput));//先通过inputstreamreader进行流转化,在实例化bufferedreader,接收内容
			String eline = "";
			while ((eline = errorReader.readLine()) != null) {//循环读取
				System.out.println(eline);//输出
				}
			errorReader.close();//此处有依赖关系,先关闭errorReader
			errorInput.close();
			} catch (IOException e) {
				output("执行" + cmd + "失败!");
				e.printStackTrace();
				}
		return cpu_result;
	}
	//获取内存信息
	public int getMemInfo(String info) {
		int result = 0;
		Pattern r = Pattern.compile(" [0-9]+ ");
		Matcher m = r.matcher(info);
		if (m.find()) {
			System.out.println(m.group());
			result = changeStringToInt(m.group().trim());
			}
		return result;
		}
	//获取cpu运行信息
	public double getCpuInfo(String info) {
		String percent = info.substring(0, info.indexOf("%"));
		double result = changeStringToDouble(percent.trim());
		return result;
	}
	//获取cpu运行信息
	public int getCpuDate(String info) {
		Pattern pattern = Pattern.compile(" [0-9]*%");
		Matcher matcher = pattern.matcher(info);
		if (matcher.find()) {
			output(matcher.group());
		}
		String date = matcher.group().trim();
		output(date.substring(0, date.length() -1 ));
		return changeStringToInt(date.substring(0, date.length() -1 ));
	}
	
	public int getVss(String info) {
		Pattern pattern = Pattern.compile(" [0-9]+K");
		Matcher matcher = pattern.matcher(info);
		if (matcher.find()) {
			output(matcher.group());
		}
		String date = matcher.group().trim();
//		output(date.substring(0, date.length() -1));
		return changeStringToInt(date.substring(0, date.length() -1));
	}
	public int getRss(String info) {
		Pattern pattern = Pattern.compile("K +[0-9]+K");
		Matcher matcher = pattern.matcher(info);
		if (matcher.find()) {
			output(matcher.group());
		}
		String date = matcher.group().substring(1, matcher.group().length() - 1);
//		output(date.trim());
		return changeStringToInt(date.trim());
	}
	
	//把string类型转化为double
	public Double changeStringToDouble (String text) {
//		return Integer.parseInt(text);
		return Double.valueOf(text);
	}
	//把string类型转化为int
	public int changeStringToInt (String text) {
//		return Integer.parseInt(text);
		return Integer.valueOf(text);
	}
	public void output(String text) {//明显输出
		System.out.println(text);
	}
	public void output(double num) {//明显输出
		System.out.println(num);
	}
	public void output(int num) {//方法重载
		System.out.println("===="+num+"====");
	}	
		
	}</pre><br>
<p></p>
<br>
<p>下面是在调试代码中如何使用多线程的方法:</p>
<p></p>
<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" οnclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" target="_blank">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" οnclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" target="_blank">copy</a><div style="position: absolute; left: 487px; top: 5554px; width: 18px; height: 18px; z-index: 99;"><embed id="ZeroClipboardMovie_2" src="" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="18" height="18" name="ZeroClipboardMovie_2" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=2&width=18&height=18" wmode="transparent"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" οnclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" target="_blank">print</a></span><a href="#" class="About" title="?" οnclick="dp.sh.Toolbar.Command('About',this);return false;" target="_blank">?</a></div></div><ol start="1" class="dp-xml"><li class="alt"><span><span class="attribute">jarName</span><span> = </span><span class="attribute-value">"Demostudent"</span><span>;</span><span class="attribute">testClass</span><span>=</span><span class="attribute-value">"student.Student"</span><span>;</span><span class="attribute">testName</span><span>=</span><span class="attribute-value">"testLittle"</span><span>;  </span></span></li><li class=""><span>        PerformanceTest.getInstance().start();//启动线程  </span></li><li class="alt"><span>        new UiAutomatorHelper(jarName, testClass, testName);//调试用例  </span></li><li class=""><span>        <span class="attribute">PerformanceTest.key</span><span> = </span><span class="attribute-value">false</span><span>;//结束线程  </span></span></li></ol></div><pre code_snippet_id="2547879" snippet_file_name="blog_20170824_2_8135850" name="code" class="html" style="display: none;">jarName = "Demostudent";testClass="student.Student";testName="testLittle";
		PerformanceTest.getInstance().start();//启动线程
		new UiAutomatorHelper(jarName, testClass, testName);//调试用例
		PerformanceTest.key = false;//结束线程</pre><br>
另外一种调用方法:
<p></p>
<p></p>
<div class="dp-highlighter bg_java"><div class="bar"><div class="tools"><b>[java]</b> <a href="#" class="ViewSource" title="view plain" οnclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" target="_blank">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" οnclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" target="_blank">copy</a><div style="position: absolute; left: 485px; top: 5765px; width: 18px; height: 18px; z-index: 99;"><embed id="ZeroClipboardMovie_3" src="" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="18" height="18" name="ZeroClipboardMovie_3" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=3&width=18&height=18" wmode="transparent"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" οnclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" target="_blank">print</a></span><a href="#" class="About" title="?" οnclick="dp.sh.Toolbar.Command('About',this);return false;" target="_blank">?</a></div></div><ol start="1" class="dp-j"><li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">static</span><span> </span><span class="keyword">void</span><span> main(String[] args) </span><span class="keyword">throws</span><span> ClassNotFoundException, SQLException, InterruptedException, IOException, ParseException {  </span></span></li><li class=""><span>    jarName = <span class="string">"Demostudent"</span><span>;testClass=</span><span class="string">"student.Student"</span><span>;testName=</span><span class="string">"testTest"</span><span>;  </span></span></li><li class="alt"><span>    PerformanceTest performanceTest = <span class="keyword">new</span><span> PerformanceTest();  </span></span></li><li class=""><span>    performanceTest.start();  </span></li><li class="alt"><span>    <span class="keyword">new</span><span> UiAutomatorHelper(jarName, testClass, testName);  </span></span></li><li class=""><span>    performanceTest.key = <span class="keyword">false</span><span>;  </span></span></li><li class="alt"><span>}  </span></li></ol></div><pre code_snippet_id="2547879" snippet_file_name="blog_20170823_2_832418" name="code" class="java" style="display: none;">	public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException, IOException, ParseException {
		jarName = "Demostudent";testClass="student.Student";testName="testTest";
		PerformanceTest performanceTest = new PerformanceTest();
		performanceTest.start();
		new UiAutomatorHelper(jarName, testClass, testName);
		performanceTest.key = false;
	}</pre><br>
<p>下面是如何将数据保存到数据库中的方法:</p>
<p></p>
<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" οnclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" target="_blank">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" οnclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" target="_blank">copy</a><div style="position: absolute; left: 487px; top: 6030px; width: 18px; height: 18px; z-index: 99;"><embed id="ZeroClipboardMovie_4" src="" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="18" height="18" name="ZeroClipboardMovie_4" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=4&width=18&height=18" wmode="transparent"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" οnclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" target="_blank">print</a></span><a href="#" class="About" title="?" οnclick="dp.sh.Toolbar.Command('About',this);return false;" target="_blank">?</a></div></div><ol start="1" class="dp-xml"><li class="alt"><span><span>public void saveMemAndCpuResult(int test_mark, double cpu_result, int mem_result) throws SQLException {  </span></span></li><li class=""><span>        if (<span class="attribute">mem_result</span><span> == 0) {//过滤掉无用数据  </span></span></li><li class="alt"><span>            return;  </span></li><li class=""><span>        }  </span></li><li class="alt"><span>        getConnection();  </span></li><li class=""><span>        if (!connection.isClosed()) {  </span></li><li class="alt"><span>            outputSuccess();  </span></li><li class=""><span>            Statement <span class="attribute">statement</span><span> = </span><span class="attribute-value">connection</span><span>.createStatement();  </span></span></li><li class="alt"><span>            String <span class="attribute">sql</span><span> = </span><span class="attribute-value">"INSERT INTO result (test_mark,cpu_result,mem_result) VALUES ("</span><span> + test_mark +"," + cpu_result + "," + mem_result + ");";  </span></span></li><li class=""><span>//          output(sql);  </span></li><li class="alt"><span>            statement.executeUpdate(sql);  </span></li><li class=""><span>        }  </span></li><li class="alt"><span>    }  </span></li><li class=""><span>    public void saveMemAndCpuResult(int test_mark, int cpu_result, int vss, int rss) throws SQLException {  </span></li><li class="alt"><span>        if (vss * <span class="attribute">rss</span><span> == 0) {//过滤掉无用数据  </span></span></li><li class=""><span>            return;  </span></li><li class="alt"><span>        }  </span></li><li class=""><span>        getConnection();  </span></li><li class="alt"><span>        if (!connection.isClosed()) {  </span></li><li class=""><span>            outputSuccess();  </span></li><li class="alt"><span>            Statement <span class="attribute">statement</span><span> = </span><span class="attribute-value">connection</span><span>.createStatement();  </span></span></li><li class=""><span>            String <span class="attribute">sql</span><span> = </span><span class="attribute-value">"INSERT INTO result (test_mark,cpu_result,vss,rss) VALUES ("</span><span> + test_mark +"," + cpu_result + "," + vss + "," + rss + ");";  </span></span></li><li class="alt"><span>//          output(sql);  </span></li><li class=""><span>            statement.executeUpdate(sql);  </span></li><li class="alt"><span>        }  </span></li><li class=""><span>    }  </span></li></ol></div><pre code_snippet_id="2547879" snippet_file_name="blog_20170824_4_1026230" name="code" class="html" style="display: none;">public void saveMemAndCpuResult(int test_mark, double cpu_result, int mem_result) throws SQLException {
		if (mem_result == 0) {//过滤掉无用数据
			return;
		}
		getConnection();
		if (!connection.isClosed()) {
			outputSuccess();
			Statement statement = connection.createStatement();
			String sql = "INSERT INTO result (test_mark,cpu_result,mem_result) VALUES (" + test_mark +"," + cpu_result + "," + mem_result + ");";
//			output(sql);
			statement.executeUpdate(sql);
		}
	}
	public void saveMemAndCpuResult(int test_mark, int cpu_result, int vss, int rss) throws SQLException {
		if (vss * rss == 0) {//过滤掉无用数据
			return;
		}
		getConnection();
		if (!connection.isClosed()) {
			outputSuccess();
			Statement statement = connection.createStatement();
			String sql = "INSERT INTO result (test_mark,cpu_result,vss,rss) VALUES (" + test_mark +"," + cpu_result + "," + vss + "," + rss + ");";
//			output(sql);
			statement.executeUpdate(sql);
		}
	}</pre><br>
<p></p>
<br>
<p></p>
   
</div>