/** * A tiny class to illustrate empirical timing in Java * * @author gtowell Created: Feb 9, 2020 */ public class Timer { private static final int REPS = 10; // number of trials private static final int NANOS_SEC = 1000000000; // nanosec per sec /** * A function to really do nothing * * @param data the size fo the data array affects the runtime of the method * @return the sum of the square roots of the two index variables. Why? Why not! */ public double doSomething(int[] data) { double k = 0; for (long i = 0; i < data.length; i++) { for (long j = 0; j < data.length; j++) { k += Math.sqrt(i * j); } } return k; } /** * Run an empirical study of the doSomething algorithm * * @param args */ public static void main(String[] args) { Timer timer = new Timer(); long data[] = new long[REPS]; for (int j = 1000; j < 10001; j = j + 1000) { for (int i = 0; i < REPS; i++) { long start = System.nanoTime(); timer.doSomething(new int[j]); long finish = System.nanoTime(); data[i] = (finish - start); System.out.println(String.format("%d %.4f", j, (double) (finish - start) / NANOS_SEC)); } } } }