Java mean of elapsed time

144 Views Asked by At

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]);
        }
    }
}
1

There are 1 best solutions below

0
Basil Bourque On

Start your timing with:

long startNanos= System.nanoTime() ;

Notice that System.nanoTime() returns a long, not the double seen in your code.

End your timing with:

Duration elapsed = Duration.ofNanos( System.nanoTime() - startNanos ) ;

Make a list to track multiple durations.

List< Duration > elapsedDurations = new ArrayList <> () ;

Add each duration.

elapsedDurations.add( elapsed ) ;

Loop the elements of that list to calculate the mean.

long totaNanos = 0 ;
for( Duration d : elapsedDurations )
{
    totaNanos = ( totaNanos + d.toNanos() ) ;
}
long meanNanos = ( totaNanos / elapsedDurations.size() ) ;

Or, let the Java libraries do the heavy lifting for you. Calculate the mean by way of a LongSummaryStatistics object.

LongSummaryStatistics stats =
    elapsedDurations
        .stream()
        .mapToLong( Duration :: toNanos )
        .summaryStatistics();

//stats.getSum()
//stats.getCount() 
//stats.getMax() 
//stats.getMin() 
Duration mean = Duration.ofNanos( stats.getAverage() ) ;