Android代碼調試工具 traceview 和 dmtracedump的波折演繹 .

該文轉自http://blog.csdn.net/yiyaaixuexi/article/details/6716884

✿Android 程序調試工具

      Google爲我們提供的代碼調試工具的亮點:traceviewdmtracedump 。有了這兩個工具,我們調試程序分析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();  
Debug.startMethodTracing(“test”); 
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. ################################################################################  
  71. ########################## Script starts from here #############################  
  72. ################################################################################  
  73. if len(sys.argv) < 2:    
  74.     print 'No input file specified.'    
  75.     sys.exit()  
  76. if not (os.path.exists(sys.argv[1])):  
  77.     print "input file not exists"  
  78.     sys.exit()  
  79. #Now handle the text part   
  80. current_section=0  
  81. for line in open(sys.argv[1]):  
  82.     line2 = line.strip()  
  83.     if (line2.startswith("*")):  
  84.         if (line2.startswith("*version")):  
  85.             current_section=1  
  86.         else:  
  87.             if (line2.startswith("*threads")):  
  88.                 current_section=2  
  89.             else:  
  90.                 if (line2.startswith("*methods")):  
  91.                     current_section=3  
  92.                 else:   
  93.                     if (line2.startswith("*end")):  
  94.                         current_section=4  
  95.                         break  
  96.         continue  
  97.     if current_section==2:  
  98.         add_one_thread(line2)  
  99.     if current_section==3:  
  100.         add_one_method(line2)  
  101.       
  102. #Now handle the binary part   
  103. mybinfile = open(sys.argv[1], "rb")   
  104. alldata = mybinfile.read()  
  105. mybinfile.close()  
  106. pos=alldata.find("SLOW")  
  107. offset,=struct.unpack("H",alldata[pos+6:pos+8])  
  108. pos2=pos+offset #pos2 is where the record begin  
  109. numofrecords = len(alldata) - pos2  
  110. numofrecords = numofrecords / 9  
  111. for i in xrange(numofrecords):  
  112.     add_one_record(alldata[pos2 + i * 9:pos2 + i * 9 + 9])  
  113. my_stack=[0]  
  114. for onerecord in all_records:  
  115.     thread_id=onerecord[0];      
  116.     method_id=onerecord[1];  
  117.     action=onerecord[2];  
  118.     time=onerecord[3];  
  119.     if(action==0):  
  120.         if(len(my_stack) > 1):  
  121.             parent_method_id=my_stack[-1]  
  122.             handle_one_call(parent_method_id,method_id)  
  123.         my_stack.append(method_id)  
  124.     else:  
  125.         if(action==1):  
  126.             if(len(my_stack) > 1):  
  127.                 my_stack.pop()  
  128. gen_dot_script_file()  
  129. os.system("dot -Tjpg graph.dot -o output.jpg;rm -f graph.dot");  
#!/usr/bin/env python
"""
turn the traceview data into a jpg pic, showing methods call relationship
"""
import sys
import os
import struct
import re
################################################################################
########################  Global Variable  #####################################
################################################################################
target_thread=1 #the thread that we want to track, filt out other threads
#all_actions = ["enter","exit","exception","reserved"]
all_threads = {}
all_methods = {}
all_records = []
parent_methods = {}
child_methods = {}
method_calls = {}
################################################################################
##############################   Methods   #####################################
################################################################################
def add_one_thread(line):
    fields = line.split("/t")
    all_threads[int(fields[0],10)]=fields
def add_one_method(line):
    fields = line.split("/t")
    all_methods[int(fields[0],16)]=fields
def add_one_record(one):
    thread_id,=struct.unpack("B",one[:1])
    if (thread_id == target_thread):
        tmp,=struct.unpack("L",one[1:5])
        method_id= (tmp / 4) * 4;
        method_action= tmp % 4;
        time_offset,=struct.unpack("L",one[5:])
        all_records.append([thread_id, method_id, method_action, time_offset])
def handle_one_call(parent_method_id,method_id):
    if not (parent_methods.has_key(parent_method_id)):
        parent_methods[parent_method_id]=1
    if not (child_methods.has_key(method_id)):
        child_methods[method_id]=1
    if method_calls.has_key(parent_method_id):
        if method_calls[parent_method_id].has_key(method_id):
            method_calls[parent_method_id][method_id]+=1
        else:
            method_calls[parent_method_id][method_id]=1
    else:
        method_calls[parent_method_id]={}
        method_calls[parent_method_id][method_id]=1
def gen_funcname(method_id):
    r1=re.compile(r'[/{1}lt;>]')
    str1=r1.sub("_",all_methods[method_id][1])
    str2=r1.sub("_",all_methods[method_id][2])
    return str1+"_"+str2
def gen_dot_script_file():
    myoutfile = open("graph.dot", "w")
    myoutfile.write("digraph vanzo {/n/n");
    for one in all_methods.keys():
        if parent_methods.has_key(one):
            myoutfile.write(gen_funcname(one)+"  [shape=rectangle];/n")
        else:
            if child_methods.has_key(one):
                myoutfile.write(gen_funcname(one)+"  [shape=ellipse];/n")
    for one in method_calls.keys():
        for two in method_calls[one]:
                myoutfile.write(gen_funcname(one) + ' -> ' + gen_funcname(two) +  ' [label="' + str(method_calls[one][two]) + '"  fontsize="10"];/n')
    myoutfile.write("/n}/n");
    myoutfile.close
    
################################################################################
########################## Script starts from here #############################
################################################################################
if len(sys.argv) < 2:  
    print 'No input file specified.'  
    sys.exit()
if not (os.path.exists(sys.argv[1])):
    print "input file not exists"
    sys.exit()
#Now handle the text part
current_section=0
for line in open(sys.argv[1]):
    line2 = line.strip()
    if (line2.startswith("*")):
        if (line2.startswith("*version")):
            current_section=1
        else:
            if (line2.startswith("*threads")):
                current_section=2
            else:
                if (line2.startswith("*methods")):
                    current_section=3
                else: 
                    if (line2.startswith("*end")):
                        current_section=4
                        break
        continue
    if current_section==2:
        add_one_thread(line2)
    if current_section==3:
        add_one_method(line2)
    
#Now handle the binary part
mybinfile = open(sys.argv[1], "rb") 
alldata = mybinfile.read()
mybinfile.close()
pos=alldata.find("SLOW")
offset,=struct.unpack("H",alldata[pos+6:pos+8])
pos2=pos+offset #pos2 is where the record begin
numofrecords = len(alldata) - pos2
numofrecords = numofrecords / 9
for i in xrange(numofrecords):
    add_one_record(alldata[pos2 + i * 9:pos2 + i * 9 + 9])
my_stack=[0]
for onerecord in all_records:
    thread_id=onerecord[0];    
    method_id=onerecord[1];
    action=onerecord[2];
    time=onerecord[3];
    if(action==0):
        if(len(my_stack) > 1):
            parent_method_id=my_stack[-1]
            handle_one_call(parent_method_id,method_id)
        my_stack.append(method_id)
    else:
        if(action==1):
            if(len(my_stack) > 1):
                my_stack.pop()
gen_dot_script_file()
os.system("dot -Tjpg graph.dot -o output.jpg;rm -f graph.dot");


 修改,/t變爲\t,/n變爲\n。
 
在計算器的源碼onCreate中添加

 
  1. Debug.startMethodTracing(“calc”);  
  2. Log.v(LOG_TAGS”+++++++++++++++++++++++++test++++++++++++++++”);  
  3. Debug.stopMethodTracing();  
Debug.startMethodTracing(“calc”);
Log.v(LOG_TAGS”+++++++++++++++++++++++++test++++++++++++++++”);
Debug.stopMethodTracing();
   
    運行腳本得到calc.trace ,畫出out.jpg

                                  



     可當得到的trace文件比較複雜時畫圖就會崩潰。修改腳本最後執行dot命令時的參數,jpg格式太大容易崩潰,-Tjpg改爲-Tpng:gd,畫大幅png。
我拿camera做了個實驗,得到的png甚大,這是其中一角:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章