2016-01-18 40 views
0

儘管可能有類似的問題(如A),但他們的回答並不能解決我的問題。在Android中,如何以編程方式衡量執行時間開銷?

我正在使用Android Studio 1.5.1,目標是Android API 18(在Android KitKat 4.4之前,所以我正在處理Dalvik,而不是ART運行時)。

我有一個修改後的Android,它增加了使用任何變量的內存空間開銷(作者專門設計,它超出了這個問題的範圍)。例如,如果我們聲明一個整型變量,變量將以8個字節(64位)而不是4個字節(32位)存儲。此修改對於可以在修改後的Android上運行而沒有任何問題的應用程序完全透明。

我需要測量執行時間的開銷,例如,當我使用變量。

這是我到目前爲止所做的,但它似乎不工作,因爲開銷變量(在下面的代碼中方法#1的末尾)不一致,有時它是負數,正數或零。在理想的解決方案中,應該始終(或者至少大部分時間)是積極的。

 long start, end, time1, time2, overhead; 

    //Baseline 
    start = System.nanoTime(); 
    total=0; total+=1; total+=2; total+=3; total+=4; total+=5; total+=6; 
    total+=7; total+=8; total+=9; 
    end = System.nanoTime(); 
    System.out.println("********************* The sum is " + total); 
    time1 = end - start; 
    System.out.println("********************* start=" + start + " end=" + end + " time=" + time1); 

    //Method #1 
    start = System.nanoTime(); 
    total = (a0() + a1() + a2() + a3() + a4() + a5() + a6() + a7() + a8() + a9()); 
    end = System.nanoTime(); 
    System.out.println("********************* The sum is " + total); 
    time2 = end - start; 
    System.out.println("********************* start=" + start + " end=" + end + " time=" + time2); 

    overhead = time2 - time1; 
    System.out.println("********************* overhead=" + overhead);  
} 
private int a0() 
{ 
    return 0; 
} 
private int a1() 
{ 
    return 1; 
} 
private int a2() 
{ 
    return 2; 
} 
private int a3() 
{ 
    return 3; 
} 
private int a4() 
{ 
    return 4; 
} 
private int a5() 
{ 
    return 5; 
} 
private int a6() 
{ 
    return 6; 
} 
private int a7() 
{ 
    return 7; 
} 
private int a8() 
{ 
    return 8; 
} 
private int a9() 
{ 
    return 9; 
} 

我的問題是:

在Android中,如何以編程方式衡量執行時間開銷?

回答

0

你所描述的只是實驗性的錯誤。

開銷變量不一致,有時它是負數, 正數或零。在理想的解決方案中,應始終如一(或至少在大多數時間爲 )。

我沒有針對Android上的問題的確切解決方案,但是當我在其他上下文中完成實驗測試時,通常會運行多次迭代,然後除以迭代次數以獲得平均值。

下面是一些僞代碼:

int N = 10000; 

startTimer(); 
for (int i = 0; i < N; i++) { 
    runExperiment(); 
} 
stopTimer(); 

double averageRuntime = timer/N; 
0

的問題是,你正在試圖時間代碼執行比System.nanotime()分辨率更快。嘗試循環添加,例如

for (int i = 0; i < 1000; i++) { 
    total += i; 
} 

增加循環計數(1000),直到您開始獲得合理的經過時間。

相關問題