Grade 12 Computer Science · Analysing efficiency

Counting instead of measuring

Why the clock answers a different question from the one you asked.

Two seconds for you, five for a friend

Exactly the same code runs for two seconds on your computer and five seconds on a friend’s. Which of the two numbers is the cost of the code? Neither. And a loop of a thousand turns inside a loop of a thousand turns does not cost two thousand, but far more. How much, and how do you count without a clock?

In grade eight you learned that algorithms can be compared without touching a clock, and why that is preferable. Now we shall do it exactly: not merely “this grows faster”, but counting exactly how many operations are performed and drawing a conclusion from the number.

A loop inside a loop multiplies the number of operations rather than adding.
// how many times does the inner line run?
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        total += a[i][j];        // n times n
    }
}

// two loops one after the other, not nested:
// for (...n...) { }
// for (...n...) { }             // n plus n

The rule that counts nearly everything

Two laws suffice for most code. A sequence — costs add; nesting — costs multiply. Hence one loop running over all the items costs as their number, two loops one after the other cost twice that, and a loop inside a loop costs as the number of items squared. The difference between twice and squared is the whole field: the first is negligible, and the second settles whether the program survives.

The structureThe cost
A single operationOne
A loop over all the itemsAs the number of items
Two loops in sequenceThe sum of the two
A loop inside a loopThe product of the two

Example 1 — why the clock answers a different question

  1. It measures today’s machine.
  2. Tomorrow the number will differ.
  3. And the algorithm did not change.

Example 2 — why nesting multiplies

  1. The inner runs in full at every turn.
  2. And the outer turns many times.
  3. So the numbers are multiplied.
The difference between twice and squared is the whole field.