循环使用方法并使用结果

时间:2015-02-07 15:46:03

标签: java loops methods average standard-deviation

我试图循环使用此方法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++;
    }

    }
}

2 个答案:

答案 0 :(得分:0)

尝试创建大小为10的数组列表,如:

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

然后,当你找到元素时,只需添加endTime - startTime列表如:

times.add(..);

一旦完成,在你的主要方法中你可以做总和,平均如:

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

答案 1 :(得分:0)

尝试:

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);