import java.util.Random; /** * A class to measure the running time of all solutions to the Maximum Subarray problem * * @author americachambers * */ public class SubsetTester { private static final int MAX_VALUE = 10000; private static final int LENGTH = 20; private static final int BURN_IN = 50; private static Random rng = new Random(); /** * Populates array with randomly chosen positive and negative values * @param array */ public static void populateArray(int[] array) { for(int i = 0; i < array.length; i++) { array[i] = rng.nextInt(MAX_VALUE) - (MAX_VALUE/2); } } public static void main(String[] args) { // Consider different number of array lengths int[] arrayLengths = new int[LENGTH]; arrayLengths[0] = 2; for(int i = 1; i < arrayLengths.length; i++){ arrayLengths[i] = arrayLengths[i-1]*2; } // Instantiate the 2 algorithms we are comparing SubsetIfc[] algorithms = new SubsetIfc[2]; algorithms[0] = new BruteForce(); algorithms[1] = new Recursive(); // Repeatedly call, but do not time, to force Java // to compile to native code (i.e. forced optimization) int[] array = new int[100]; for(int i = 0; i < BURN_IN; i++) { populateArray(array); for(int j = 0; j < algorithms.length; j++){ algorithms[j].solve(array); } } System.out.println("Finished burn in..."); // Start the actual timed trials // For each number of days // For 10 iterations // Randomly sample new prices // Run each of the algorithms long[] times = new long[algorithms.length]; SubsetInfo[] solutions = new SubsetInfo[algorithms.length]; long start, end; int timedIterations = 10; for(int i = 0; i < arrayLengths.length; i++) { int length = arrayLengths[i]; array = new int[length]; for(int j = 0; j < timedIterations; j++){ populateArray(array); // Run and time each algorithm for(int k = 0; k < algorithms.length; k++){ start = System.nanoTime(); solutions[k] = algorithms[k].solve(array); end = System.nanoTime(); times[k] += (end - start); } // Check all answers for(int k = 1; k < algorithms.length; k++){ assert(solutions[k-1].sum == solutions[k].sum); } } // Print out the time in microseconds System.out.print(arrayLengths[i] + "\t"); for(int k = 0; k < times.length; k++){ System.out.print((times[k]/1000)/timedIterations+ "\t"); } System.out.println(); } } }