Grade 8 Computer Science · Efficiency
Counting operations, not measuring time
Why the clock lies, and what is counted instead.
The same program, two different times
You ran a program twice in a row, on the same computer with the same data, and got two different times. If the clock does not agree with itself, how can it compare two algorithms at all? There is another number, one you can work out without running anything.
We saw that there are several correct solutions to one problem, and that they differ in cost. Now a way to measure that cost is needed — and precisely the obvious way, measuring how long it took, is the poor way.
| The way | What the problem is |
|---|---|
| Measuring time | Depends on the computer and the moment |
| Counting operations | No problem — that is the way |
def contains(items, target):
for item in items: # runs once per item
if item == target: # one comparison each round
return True
return FalseThe worst case is counted
An algorithm has three possible numbers: how many operations in the best case, on average, and in the worst. Nearly always the worst is counted, and not because we are pessimists — but because it is the only one giving a guarantee. If I said the search takes at most a thousand checks, that is a claim that can be relied on in any situation. The best case guarantees nothing, because it depends on luck, and the average requires knowing how the input is distributed — knowledge we usually do not have. This is the same distinction seen about evidence: a claim is worth as much as it covers.
Example 1 — why two runs give different numbers
- The first run was measured with the computer free.
- In the second something else ran in the background.
- The time differs, and the algorithm is identical.
- So time does not measure the algorithm.
Example 2 — why the worst case guarantees
- The target item is at the end of the list.
- Or is not in it at all.
- Then all the items are checked.
- That is the upper bound that can be guaranteed.