/** * file : SortPerf.java * desc : Sort performance benchmarking */ import Timer.*; import java.util.Random; import java.io.*; class SortPerf { private static final String outFilename = "select.dat"; private static final int incN = 5; private static final int maxN = 175; private static final int numTrials = 200; /** * post : Opens the output file `outFilename' (above). * Times a sorting algorithm on data for arrays * of size incN, 2*incN, ..., maxN and writes * the timing data to the output file. * * For an array of each size, sorts the random * data numTrials times to get an average * running time per trial. */ public static void main( String[] argv ) throws IOException { /* open the output file */ PrintWriter timings = openOutputFile( outFilename ); // print a header on the output file timings.println( "# Results for " + numTrials + " trials" ); timings.println( "# n time (msec)" ); timings.println( "# ---------------" ); /* do the timing */ Timer stopWatch = new Timer(); for( int n = incN; n <= maxN; n += incN ) { System.out.println( "timing n == " + n + " ... " ); stopWatch.reset(); for( int t = 0; t < numTrials; t++ ) { int[] data = randomData( n ); stopWatch.start(); /* Call the appropriate sorting routine here */ SelectionSort.sort( data ); stopWatch.stop(); } long totalTime = stopWatch.elapsed(); // output timings.println( n + " " + totalTime ); } /* fin! */ timings.close(); System.out.println( "done! results in `" + outFilename + "'" ); } /** * post : prints the contents of A to standard out */ private static void printData( int[] A ) { for( int i = 0; i < A.length - 1; i++ ) { System.out.print( A[i] + ", " ); } if( A.length-1 >= 0 ) System.out.println( A[A.length-1] ); } private static final long INIT_SEED = 1234567; /** * pre : n > 0 * * post : returns an array of `n' randomly selected * integers. */ private static int[] randomData( int n ) { // choose same sequence of random numbers so that // we can fairly compare our sorting algorithms Random randGen = new Random( INIT_SEED ); int[] newData = new int[ n ]; for( int i = 0; i < n; i++ ) { newData[i] = randGen.nextInt(); } return newData; } /** * post : returns an output file stream corresponding * to the file given by `filename' */ private static PrintWriter openOutputFile( String filename ) throws IOException { return new PrintWriter( new FileOutputStream(filename) ); } } // eof