//Use this file as a basis for your experiments import java.io.FileNotFoundException; import java.io.PrintWriter; /** * Example timing analysis for linear search */ public class Timing { /** * Timing function for LinkedList add to end * @param n Size of experiment * @param k Number of times to repeat experiment * @return Seconds taken for experiment */ public static double TimeFunction(int n, int k) { // Optional initialization before timing int[] arr = new int[n]; for(int i = 0; i < n; ++i) arr[i] = (int)(Math.random() * Integer.MAX_VALUE); // Timing - repeat the experiment k times long start = System.nanoTime(); for(int i = 0; i < k; ++i) { // Example function of linear search int key = -1; for(int x : arr) if(x == key) System.out.print("Error"); } long stop = System.nanoTime(); // Compute average from elapsed time double sec = (stop - start)/(double)1e9/k; return sec; } /** * Run all timing functions and output to terminal and csv file * @param args Command-line arguments. Ignored here. * @exception FileNotFoundException If system cannot open filename, exception. */ public static void main(String[] args) throws FileNotFoundException { // Output devised to go to terminal/console AND csv (excel) file PrintWriter pw = new PrintWriter("data.csv"); // Output title row System.out.printf("%10s %15s", "N", "Time"); pw.print("N,Time"); int N = 20000; // Upper limit of input size to the experiment for(int n = 2; n < N; n*=2) { // Use powers of 2 only // Start a new row System.out.println(); pw.println(); // Output size column System.out.printf("%10s ", n); pw.print(n); int repeats = Math.max(10, N/n); // Output data cell for second column double tall = TimeFunction(n, repeats); System.out.printf("%15e", tall); pw.print("," + tall); } System.out.println(); // Always flush and close! pw.flush(); pw.close(); } }