2015-02-07 36 views
1

我試圖通過這個方法循環10次,搜索一個數字數組捕獲納秒運行時間並打印結果。然後我想要10次運行時間並找出平均值和標準偏差。 有沒有辦法在10次運行後捕捉時間並使用結果來查找我的平均值和標準偏差? 這是我到目前爲止有:循環遍歷一個方法並使用結果

public class Search { 
    public static int Array[] = new int[100]; 
    //Building my array with 100 numbers in sequential order 
    public static void createArray(){ 


     int i = 0; 
     for(i = 0; i<Array.length; i++) 
      Array[i] = i + 1; 
     int check[] = {5, 15, 12}; 
     int target = check[2]; 
     boolean found = false; 
     int j = 0; 
     long startTime = System.nanoTime(); 
    for(j=0; j<Array.length;j++){ 
     if(Array[j] == target){ 
      long endTime = System.nanoTime(); 

      System.out.print(endTime - startTime + "ms" + "\t\t"); 
      found = true; 



     break; 
     } 
    } 
     if(found){ 
      //System.out.println("got you! "+ target + " is at index "+ j +"\t");..... just to test if it was working 

     } 
     else{ 
      System.out.println("not available"); 


     } 

    } 
// Printing header 
    public static void main(String[]args){ 
     System.out.print("First run\tSecond run\tThird run\tFourth run\tFifth run\tSixth run\tSeventh run\tEight run\tNinth run\tTenth run\tAverage \tStandard deviation\n"); 
    // looping through the method 10 times 
    int i=0; 
    while(i<10){ 

     createArray(); 


     i++; 
    } 

    } 
} 

回答

0

Try:

long sum = 0; 
long sumSquare = 0; 
for(int c = 0 ; c < 10 ; c++) { 
    long start = System.nanoTime(); 
    // do work 
    long end = System.nanoTime(); 
    sum += end - start; 
    sumSquare += Math.pow(end - start, 2); 
} 
double average = (sum * 1D)/10; 
double variance = (sumSquare * 1D)/10 - Math.pow(average, 2); 
double std = Math.sqrt(variance); 
0

嘗試創建大小爲10的像一個數組列表:

private static List<Long> times = new ArrayList<>(10); 

然後,當你發現的元素只需添加結束時間 - 開始時間列出,如:

times.add(..); 

而一旦這樣做了,在你的主要方法,你可以做求和,平均值,如:

long totalTime = 0; 
for (Long time : times) { 
    totalTime += time; 
} 
//print average by dividing totalTime by 10. 
相關問題