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.

As the data grows, the difference between the shapes becomes decisive.
The wayWhat the problem is
Measuring timeDepends on the computer and the moment
Counting operationsNo 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 False

The 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

  1. The first run was measured with the computer free.
  2. In the second something else ran in the background.
  3. The time differs, and the algorithm is identical.
  4. So time does not measure the algorithm.

Example 2 — why the worst case guarantees

  1. The target item is at the end of the list.
  2. Or is not in it at all.
  3. Then all the items are checked.
  4. That is the upper bound that can be guaranteed.
Count the significant repeated operation — here, a comparison — and not the seconds.