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.
// 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 nThe 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 structure | The cost |
|---|---|
| A single operation | One |
| A loop over all the items | As the number of items |
| Two loops in sequence | The sum of the two |
| A loop inside a loop | The product of the two |
Example 1 — why the clock answers a different question
- It measures today’s machine.
- Tomorrow the number will differ.
- And the algorithm did not change.
Example 2 — why nesting multiplies
- The inner runs in full at every turn.
- And the outer turns many times.
- So the numbers are multiplied.