如果覺得程式跑太慢,可以利用這個工具
來看看是那個 function 跑了最久,或是比預期的久
就可以想辦法改進
直接來看code
TraceViewTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package traceview.test; | |
import android.app.Activity; | |
import android.os.Bundle; | |
import android.os.Debug; | |
public class TraceViewTest extends Activity { | |
myThread thread1, thread2; | |
/** Called when the activity is first created. */ | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
Debug.startMethodTracing("TraceViewTest"); | |
setContentView(R.layout.main); | |
thread1 = new myThread(1000); | |
thread2 = new myThread(2000); | |
thread1.start(); | |
thread2.start(); | |
} | |
@Override | |
public void onStop() | |
{ | |
Debug.stopMethodTracing(); | |
super.onStop(); | |
} | |
} |
主要就是第13、24行,就是開始和結束 Trace 的 function
startMethodTracing 傳入的參數是輸出檔的檔名,最後會在SD卡中生出 XXX.trace 檔
記得要打開 write_external_storage 的權限
myThread.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package traceview.test; | |
public class myThread extends Thread{ | |
private int loop_times; | |
public myThread(int time) | |
{ | |
this.loop_times = time; | |
} | |
@Override | |
public void run(){ | |
int i; | |
for(i=0;i<loop_times;i++) | |
{ | |
try { | |
sleep(10); | |
} catch (InterruptedException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
} |
這只是用來測試的Thread
最後把 XXX.trace 抓出來
在 Android SDK 的 tools 裡面有一個 traceview.bat
使用 CMD 執行 traceview C:\XXX.trace (一定要打絕對路徑)
結果:
可以得到上面的時間軸以及下面每個 function 所執行的時間
Inclusive 是包括所有subfunction所執行的時間
exclusive 是只有function本身執行的時間
沒有留言:
張貼留言