/** * A Simple class to illustrate the problems with timing tasks, even on * computers with known loading * * @author gtowell Created: Sep 2020 Modified: Mar 1, 2021 gtowell Modified: Sep * 8, 2021 gtowell */ public class Timer { private static final int REPS = 2; // number of trials private static final int NANOS_SEC = 1000000000; // nanosec per sec /** * A very silly function that does a lot of work based on the size of the input * array. However, it never actually looks at the contents of that array * * @param data the input array (content ignored) * @return a largely meaningless value */ 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; } /** * The main, Does a timing test doubling the size of the input for every step * * @param args */ public static void main(String[] args) { Timer timer = new Timer(); long data[] = new long[REPS]; for (int j = 1000; j < 65001; j = j * 2) { 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)); } } } }