Lab 1 – Timing and Counting
Part 1 – Measure and count¶
Task 1 – A reliable timer¶
System.nanoTime() gives the current time in nanoseconds. One measurement is not
enough: the first runs of a method are slow (the JIT compiler is still optimising it), and
other programs may interrupt yours. Write a method that runs a piece of code several times
and keeps the best time.
static double bestTimeMs(Runnable r, int repeats) {
// ToDo: run r.run() `repeats` times, measure each run with System.nanoTime(),
// and return the smallest time in milliseconds
}Runnable lets you pass code as a parameter, with a lambda:
bestTimeMs(() -> linear(1000000), 5) times five calls of linear(1000000).
Solution
// Runs the code r several times and returns the best time in milliseconds.
static double bestTimeMs(Runnable r, int repeats) {
double best = Double.MAX_VALUE;
for (int k = 0; k < repeats; k++) {
long t0 = System.nanoTime();
r.run();
double ms = (System.nanoTime() - t0) / 1e6;
best = Math.min(best, ms);
}
return best;
}Task 2 – The doubling experiment¶
Write a linear method (one loop of n steps) and a quadratic one (two nested loops of n
steps each). Time them for n, 2n, 4n, … and print the ratio between consecutive times.
static long sink; // results are stored here so the JIT cannot skip the loops
static void linear(int n) {
long s = 0;
for (int i = 0; i < n; i++)
s += i % 7;
sink += s;
}
static void quadratic(int n) {
long s = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
s += (i ^ j) & 1;
sink += s;
}Complete main: warm the methods up first, then print a table with n, the time and the
ratio T(2n) / T(n).
Solution
// warm-up: let the JIT compiler optimise the methods before measuring
bestTimeMs(() -> linear(1_000_000), 20);
bestTimeMs(() -> quadratic(1000), 20);
System.out.println(" n linear(ms) ratio");
double prev = 0;
for (int n = 1_000_000; n <= 16_000_000; n *= 2) {
final int size = n;
double t = bestTimeMs(() -> linear(size), 5);
System.out.printf("%9d %10.2f %6s%n", n, t,
prev == 0 ? "" : String.format("%.1f", t / prev));
prev = t;
}
System.out.println(" n quadratic(ms) ratio");
prev = 0;
for (int n = 2000; n <= 16000; n *= 2) {
final int size = n;
double t = bestTimeMs(() -> quadratic(size), 3);
System.out.printf("%6d %12.2f %8s%n", n, t,
prev == 0 ? "" : String.format("%.1f", t / prev));
prev = t;
}Sample output (your times will differ, the ratios should not):
n linear(ms) ratio
1000000 1.59
2000000 2.81 1.8
4000000 5.46 1.9
8000000 11.03 2.0
16000000 24.84 2.3
n quadratic(ms) ratio
2000 2.45
4000 10.51 4.3
8000 42.23 4.0
16000 162.09 3.8Task 3 – Counting steps: two GCD algorithms¶
Timing depends on the machine; counting the basic operations does not. Add a counter to the two GCD algorithms of the slides: consecutive integer checking and Euclid’s algorithm.
static int steps; // number of loop iterations of the last call
static int gcd1(int m, int n) { // consecutive integer checking
// ToDo: start with t = min(m, n) and decrease t until it divides m and n
// count the iterations in `steps`
}
static int gcd2(int m, int n) { // Euclid: gcd(m, n) = gcd(n, m % n)
// ToDo: count the iterations in `steps`
}Solution
static int steps; // number of loop iterations of the last call
static int gcd1(int m, int n) { // consecutive integer checking
steps = 0;
int t = Math.min(m, n);
while (m % t != 0 || n % t != 0) {
t--;
steps++;
}
return t;
}
static int gcd2(int m, int n) { // Euclid
steps = 0;
while (n != 0) {
int rem = m % n;
m = n;
n = rem;
steps++;
}
return m;
}Test with:
int[][] inputs = {{14800, 5000}, {1000000, 999999}, {60, 24}};
for (int[] in : inputs) {
int g1 = gcd1(in[0], in[1]);
int s1 = steps;
int g2 = gcd2(in[0], in[1]);
int s2 = steps;
System.out.printf("gcd(%d, %d) = %d: %d steps vs %d steps%n",
in[0], in[1], g1, s1, s2);
}Expected output:
gcd(14800, 5000) = 200: 4800 steps vs 3 steps
gcd(1000000, 999999) = 1: 999998 steps vs 2 steps
gcd(60, 24) = 12: 12 steps vs 2 stepsPart 2 – Use the JDK¶
Challenge 1 – Same question, three containers¶
Store the numbers in an ArrayList, a HashSet and a sorted int[].
Then answer 10,000 questions “is k present?” with each structure, and time them with
your bestTimeMs.
Solution
int n = 100_000;
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
int[] sorted = new int[n];
for (int i = 0; i < n; i++) {
list.add(i);
set.add(i);
sorted[i] = i;
}
Random rnd = new Random(42);
int[] keys = new int[10_000];
for (int i = 0; i < keys.length; i++)
keys[i] = rnd.nextInt(2 * n); // about half are absent
double tList = bestTimeMs(() -> {
for (int k : keys) if (list.contains(k)) sink++;
}, 3);
double tSet = bestTimeMs(() -> {
for (int k : keys) if (set.contains(k)) sink++;
}, 3);
double tBin = bestTimeMs(() -> {
for (int k : keys) if (Arrays.binarySearch(sorted, k) >= 0) sink++;
}, 3);
System.out.printf("ArrayList.contains : %8.2f ms%n", tList);
System.out.printf("HashSet.contains : %8.2f ms%n", tSet);
System.out.printf("Arrays.binarySearch : %8.2f ms%n", tBin);Sample output:
ArrayList.contains : 2655.00 ms
HashSet.contains : 1.30 ms
Arrays.binarySearch : 0.92 msThe ArrayList is about a thousand times slower: each contains scans up to 100,000
elements. Choosing the container is choosing the algorithm.
Challenge 2 – Repeated values among a million numbers¶
Generate 1,000,000 random numbers with new Random(1) and nextInt(10_000_000). Count
how many values are repeats of an earlier one, and how many distinct values there are.
Comparing all pairs would take comparisons; a HashSet needs one pass.
Hint: set.add(x) returns false when x is already in the set.
Solution
Random r = new Random(1);
int[] a = new int[1_000_000];
for (int i = 0; i < a.length; i++)
a[i] = r.nextInt(10_000_000);
Set<Integer> seen = new HashSet<>();
int dups = 0;
for (int x : a)
if (!seen.add(x)) // add() returns false if x was already there
dups++;
System.out.println("repeated values: " + dups);
System.out.println("distinct values: " + seen.size());Expected output:
repeated values: 48273
distinct values: 951727