I am trying to calculate the mean of all elapsed times in my loop. Can anyone help me out? My issue is I am unsure how to use the total time of all of the loops to calculate the mean.
package ClassOne;
import java.util.Random;
public class SelectionProgram {
public static void main(String[] args) {
for (int j = 0; j < 10000;j++) {
double startTime = System.nanoTime();
Random rd = new Random();
int [] n = new int [100];
for (int i = 0; i < n.length; i++) {
n[i] = rd.nextInt();
}
SelectionSort(n);
printArray(n);
double endTime = System.nanoTime();
double elapsedTime = endTime-startTime;
System.out.println(" Elapsed Time:" + elapsedTime);
}
}
public static int[] SelectionSort(int[] A) {
int k;
int temp;
for (int i=0; i<A.length-1; i++) {
k=i;
for (int j=i+1; j<=A.length-1; j++) {
if (A[j]<A[k]) {
k=j;
}
}
temp = A[i];
A[i] = A[k];
A[k] = temp;
}
return A;
}
public static void printArray(int[] A) {
for(int i = 0; i<A.length; i++) {
System.out.println(A[i]);
}
}
}
Start your timing with:
Notice that
System.nanoTime()returns along, not thedoubleseen in your code.End your timing with:
Make a list to track multiple durations.
Add each duration.
Loop the elements of that list to calculate the mean.
Or, let the Java libraries do the heavy lifting for you. Calculate the mean by way of a
LongSummaryStatisticsobject.