zoukankan      html  css  js  c++  java
  • [Android]Android代码调试工具: Traceview和Dmtracedump

    ✿Android 程序调试工具

    Google为我们提供的代码调试工具的亮点:traceview 和 dmtracedump 。有了这两个工具,我们调试程序分析bug就非常得心应手了。traceview帮助我们分析程序性能,dmtracedump生成函数调用图。遗憾的是,google提供的dmtracedump是个失败的工具,并不能绘图,本文会详细介绍解决方案,实现绘图。

    ✿生成.trace文件

    android.os.Debug类,其中重要的两个方法Debug.startMethodTracing()和Debug.stopMethodTracing()。这两个方法用来创建.trace文件,将从Debug.startMethodTracing()开始,到Debug.stopMethodTracing()结束,期间所有的调用过程保存在.trace文件中,包括调用的函数名称和执行的时间等信息。
    把下面代码分别在加在调试起始代码的位置,和终止位置。

    1. Debug.startMethodTracing(“test”);
    2. Debug.stopMethodTracing();

    其中参数test是要创建的trace文件的名称,test.trace。默认路径是/sdcard/test.trace,也可以自己制定/data/log/test,表示文件在/data/log/test.trace。

    ✿traceview

    在SDK中执行  :

    ./traceview test.trace

    我们可以得到

    1.程序中每个线程调用方法的启动和停止时间

    2.函数执行的信息和效率分析

    ✿dmtracedump

         dmtracedump原本的用意是将整个调用过程和时间分析结合,以函数调用图的形式表现出来。可是google这个项目一直处于broken状态,迟迟不能得到完善。现在的dmtracdump只有-o选项可以使用,在终端上列出函数调用信息,和traceview功能相似,如果执行./dmtracedump –g test.png test.trace就会卡住不动。

        起初我以为是test.trace文件的问题,对文件的结束符稍作修改,画出了一副雷人的图片:

    后来,搜到了网络上有牛人提供了dmtracedump的替代(这是原文链接),是一个python脚本,借助dot来绘制矢量图。python脚本一定要注意对齐格式,对齐缩进就是他的逻辑结构。

     
    1. #!/usr/bin/env python
    2. """
    3. turn the traceview data into a jpg pic, showing methods call relationship
    4. """
    5. import sys
    6. import os
    7. import struct
    8. import re
    9. ################################################################################
    10. ########################  Global Variable  #####################################
    11. ################################################################################
    12. target_thread=1 #the thread that we want to track, filt out other threads
    13. #all_actions = ["enter","exit","exception","reserved"]
    14. all_threads = {}
    15. all_methods = {}
    16. all_records = []
    17. parent_methods = {}
    18. child_methods = {}
    19. method_calls = {}
    20. ################################################################################
    21. ##############################   Methods   #####################################
    22. ################################################################################
    23. def add_one_thread(line):
    24.     fields = line.split("/t")
    25.     all_threads[int(fields[0],10)]=fields
    26. def add_one_method(line):
    27.     fields = line.split("/t")
    28.     all_methods[int(fields[0],16)]=fields
    29. def add_one_record(one):
    30.     thread_id,=struct.unpack("B",one[:1])
    31.     if (thread_id == target_thread):
    32.         tmp,=struct.unpack("L",one[1:5])
    33.         method_id= (tmp / 4) * 4;
    34.         method_action= tmp % 4;
    35.         time_offset,=struct.unpack("L",one[5:])
    36.         all_records.append([thread_id, method_id, method_action, time_offset])
    37. def handle_one_call(parent_method_id,method_id):
    38.     if not (parent_methods.has_key(parent_method_id)):
    39.         parent_methods[parent_method_id]=1
    40.     if not (child_methods.has_key(method_id)):
    41.         child_methods[method_id]=1
    42.     if method_calls.has_key(parent_method_id):
    43.         if method_calls[parent_method_id].has_key(method_id):
    44.             method_calls[parent_method_id][method_id]+=1
    45.         else:
    46.             method_calls[parent_method_id][method_id]=1
    47.     else:
    48.         method_calls[parent_method_id]={}
    49.         method_calls[parent_method_id][method_id]=1
    50. def gen_funcname(method_id):
    51.     r1=re.compile(r'[/{1}lt;>]')
    52.     str1=r1.sub("_",all_methods[method_id][1])
    53.     str2=r1.sub("_",all_methods[method_id][2])
    54.     return str1+"_"+str2
    55. def gen_dot_script_file():
    56.     myoutfile = open("graph.dot", "w")
    57.     myoutfile.write("digraph vanzo {/n/n");
    58.     for one in all_methods.keys():
    59.         if parent_methods.has_key(one):
    60.             myoutfile.write(gen_funcname(one)+"  [shape=rectangle];/n")
    61.         else:
    62.             if child_methods.has_key(one):
    63.                 myoutfile.write(gen_funcname(one)+"  [shape=ellipse];/n")
    64.     for one in method_calls.keys():
    65.         for two in method_calls[one]:
    66.                 myoutfile.write(gen_funcname(one) + ' -> ' + gen_funcname(two) +  ' [label="' + str(method_calls[one][two]) + '"  fontsize="10"];/n')
    67.     myoutfile.write("/n}/n");
    68.     myoutfile.close
    69. ################################################################################
    70. ########################## Script starts from here #############################
    71. ################################################################################
    72. if len(sys.argv) < 2:
    73.     print 'No input file specified.'
    74.     sys.exit()
    75. if not (os.path.exists(sys.argv[1])):
    76.     print "input file not exists"
    77.     sys.exit()
    78. #Now handle the text part
    79. current_section=0
    80. for line in open(sys.argv[1]):
    81.     line2 = line.strip()
    82.     if (line2.startswith("*")):
    83.         if (line2.startswith("*version")):
    84.             current_section=1
    85.         else:
    86.             if (line2.startswith("*threads")):
    87.                 current_section=2
    88.             else:
    89.                 if (line2.startswith("*methods")):
    90.                     current_section=3
    91.                 else:
    92.                     if (line2.startswith("*end")):
    93.                         current_section=4
    94.                         break
    95.         continue
    96.     if current_section==2:
    97.         add_one_thread(line2)
    98.     if current_section==3:
    99.         add_one_method(line2)
    100. #Now handle the binary part
    101. mybinfile = open(sys.argv[1], "rb")
    102. alldata = mybinfile.read()
    103. mybinfile.close()
    104. pos=alldata.find("SLOW")
    105. offset,=struct.unpack("H",alldata[pos+6:pos+8])
    106. pos2=pos+offset #pos2 is where the record begin
    107. numofrecords = len(alldata) - pos2
    108. numofrecords = numofrecords / 9
    109. for i in xrange(numofrecords):
    110.     add_one_record(alldata[pos2 + i * 9:pos2 + i * 9 + 9])
    111. my_stack=[0]
    112. for onerecord in all_records:
    113.     thread_id=onerecord[0];
    114.     method_id=onerecord[1];
    115.     action=onerecord[2];
    116.     time=onerecord[3];
    117.     if(action==0):
    118.         if(len(my_stack) > 1):
    119.             parent_method_id=my_stack[-1]
    120.             handle_one_call(parent_method_id,method_id)
    121.         my_stack.append(method_id)
    122.     else:
    123.         if(action==1):
    124.             if(len(my_stack) > 1):
    125.                 my_stack.pop()
    126. gen_dot_script_file()
    127. os.system("dot -Tjpg graph.dot -o output.jpg;rm -f graph.dot");
     修改,/t变为 ,/n变为 。
    在计算器的源码onCreate中添加
    1. Debug.startMethodTracing(“calc”);
    2. Log.v(LOG_TAGS”+++++++++++++++++++++++++test++++++++++++++++”);
    3. Debug.stopMethodTracing();
        运行脚本得到calc.trace ,画出out.jpg
     
                                      
     
     
     
         可当得到的trace文件比较复杂时画图就会崩溃。修改脚本最后执行dot命令时的参数,jpg格式太大容易崩溃,-Tjpg改为-Tpng:gd,画大幅png。
    我拿camera做了个实验,得到的png甚大,这是其中一角:
     
  • 相关阅读:
    根据判断PC浏览器类型和手机屏幕像素自动调用不同CSS的代码
    c#抓取网页内容乱码的解决方案
    C#中使用正则表达式提取超链接地址的集中方法
    sql server日期时间转字符串
    DataGridView直接导出EXCEL
    sql数据库删除表的外键约束(INSERT 语句与 FOREIGN KEY 约束"XXX"冲突。该冲突发生于数据库"XXX",表"XXX", column 'XXX)
    C#抓取页面时候,获取页面跳转后的地址
    HttpWebRequest 抓取页面异常处理办法
    JQuery的Ajax跨域请求的解决方案
    mysql 事物ACID和隔离级别
  • 原文地址:https://www.cnblogs.com/webapplee/p/3774055.html
Copyright © 2011-2022 走看看