Sub topic 1
Measuring cost by input size, not by seconds
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Python: variables, loops, functions, and recursion.
- Use arrays (Python lists) and index into them.
- Work with basic algebra, including exponents.
Logarithms help in later chapters but are not needed here.
Why seconds are a poor measure
Suppose you want to know whether one algorithm is better than another. The obvious test is to run both and time them. That test has several problems.
- Hardware changes the answer. A laptop, a phone, and a cloud server run the same code at different speeds.
- Software changes the answer. The language, the interpreter version, the operating system, and other running programs all shift the timing.
- The input changes the answer. An algorithm may be fast on the list you tried and slow on another.
- Timings do not transfer. A result for 1,000 items says little about 1,000,000 items.
We want a measure that does not depend on the machine and that predicts how the cost behaves as the problem gets bigger. The way to get one is to count steps as a function of the input size.
Input size
The input size, written n, is the quantity that determines how much work the algorithm has to do. What n means depends on the problem.
| Problem | Natural meaning of `n` |
|---|---|
| Sum a list | Number of elements in the list |
| Search a sorted list | Number of elements in the list |
| Check a string for a palindrome | Number of characters |
| Test whether a number is prime by trial division | The value of the number, or the number of digits (see the warning below) |
| Visit every cell of a grid | Number of cells, or rows and columns as two separate sizes |
Some problems have more than one size. If a function takes a list of a items and a list of b items, the cost is a function of both a and b. You can write it as a function of a and b, and you should not collapse the two into one n unless you know they are equal.
Counting basic operations
Once n is fixed, we count basic operations. A basic operation is a step that takes a roughly constant amount of time, regardless of the input size. Typical examples are:
- Comparing two numbers.
- Adding two numbers.
- Reading or writing one list element by index.
- Assigning a value to a variable.
We do not count the exact number of CPU cycles. We pick the operation that dominates the work and count how many times it runs. The result is a function T(n): the number of basic operations as a function of the input size n.
Here is a small example. The function below sums a list.
def total(items):
s = 0 # 1 assignment
for x in items: # loop body runs n times
s += x # 1 addition and 1 assignment per pass
return s # 1 returnIf we count every addition, assignment, and return as one step, then T(n) = 2n + 2. If we count only the additions, then T(n) = n. The two counts differ, but both grow in direct proportion to n. Doubling the list roughly doubles the work in either case. That shared behavior is what we care about, and later chapters will show how to say it precisely.
A worked example: constant, linear, and quadratic
Three small functions show how the step count depends on n in different ways.
def first_item(items):
return items[0] # O(1): one step regardless of len(items)
def total(items):
s = 0
for x in items: # runs n times
s += x
return s # O(n)
def has_duplicate(items):
n = len(items)
for i in range(n):
for j in range(i + 1, n):
if items[i] == items[j]:
return True
return False # worst case n(n-1)/2 comparisons, which is O(n^2)The notation O(1), O(n), and O(n^2) is introduced properly in later chapters. For now, read it as "the cost grows like this."
first_itemdoes one step no matter how long the list is. A list of 10 and a list of 10 million cost the same.totaldoes one pass over the list. Its step count grows in proportion ton.has_duplicatecompares every pair of items. When there is no duplicate, the number of comparisons isn(n-1)/2.
Where does n(n-1)/2 come from? The first value of i is compared with n - 1 later items, the next with n - 2, and so on down to 0. The sum (n-1) + (n-2) + ... + 1 + 0 equals n(n-1)/2. Expanding gives n^2/2 - n/2. For large n, the n^2 term dominates, so doubling n roughly quadruples the work.
Measuring steps instead of time
You can check these claims by counting operations in code rather than timing it. The function below counts the comparisons that has_duplicate makes on a list with no duplicates.
def count_comparisons(n):
items = list(range(n)) # n distinct values, so no early exit
count = 0
for i in range(n):
for j in range(i + 1, n):
count += 1 # one comparison per inner pass
return count
for n in (10, 100, 1000):
print(n, count_comparisons(n), n * (n - 1) // 2)Running it prints:
10 45 45
100 4950 4950
1000 499500 499500The measured count matches the formula n(n-1)/2 exactly. The result is the same on any computer, because we counted steps and did not measure time. Note also the growth: going from n = 10 to n = 100 multiplies the input by 10 but the count by about 110. Going from 100 to 1000 multiplies the count by about 100.
Comparing timings and counts
Timing still has a use. It confirms that your step model matches reality. The next program times total and has_duplicate on a few sizes.
import time
def total(items):
s = 0
for x in items:
s += x
return s
def has_duplicate(items):
n = len(items)
for i in range(n):
for j in range(i + 1, n):
if items[i] == items[j]:
return True
return False
for n in (500, 1000, 2000):
items = list(range(n))
t0 = time.perf_counter()
total(items)
t1 = time.perf_counter()
has_duplicate(items)
t2 = time.perf_counter()
print(f"n={n:5d} total={t1 - t0:.6f}s has_duplicate={t2 - t1:.6f}s")The exact numbers differ from machine to machine. The pattern does not. Each time n doubles, the time for total roughly doubles, and the time for has_duplicate roughly quadruples. Very small timings can be noisy, so for serious measurement use timeit and repeat each run.
What "cost" can mean
Time is the most common cost, but it is not the only one. The same counting approach applies to other resources.
- Time: the number of basic operations.
- Space: the amount of memory used beyond the input itself. A later chapter covers this, including the call stack used by recursion.
- Other resources: disk reads, network requests, or database queries, when one of these dominates the real cost.
Pick the resource that matters for the problem, then count it as a function of n.
Choosing what to count
You may count different operations and get different formulas. This is fine as long as the chosen operation reflects the real work.
- For sorting by comparison, count comparisons.
- For searching a list, count element comparisons.
- For a loop with a heavy body, count the body's work, not the loop bookkeeping.
- For code that calls a library function, check what that function costs. The call
sum(items)is one line, but it still touches allnitems.
A common mistake is to count lines of code instead of operations executed. A single line can hide a loop. For example, x in items on a Python list scans the list and costs up to n comparisons. A second mistake is to count one run of the code and forget repetition: a one-line statement inside a loop runs once per pass.
Same size, different inputs
Two inputs of the same size can cost different amounts. Look at a linear search.
def linear_search(items, target):
for i, x in enumerate(items):
if x == target:
return i
return -1If target is the first element, the function does one comparison. If target is absent, it does n comparisons. Both inputs have size n, but the cost differs. For this reason we usually state which input we mean, such as the worst case. Later chapters treat best, worst, and average case in detail. At this stage, remember that T(n) is only well defined once you say which inputs of size n you are counting.
Seeing the growth
The diagram below shows the shape of the idea: an algorithm takes an input of size n, we count operations, and we study how the count grows.
The next chapter takes the step counts we have built here and compares how fast different ones grow.
Common mistakes
- Reporting seconds as the complexity. "It takes 2 seconds" is a measurement, not a statement about growth.
- Leaving
nundefined. Say whatnis, especially when there are two inputs or when the input is a number. - Ignoring hidden loops. Membership tests, slicing,
list.index, string concatenation in a loop, andsumall do work proportional to the data they touch. - Testing only small inputs. The difference between
nandn^2is hard to see atn = 10and obvious atn = 10,000. - Mixing up the input and its size. The list
[4, 8, 15]is the input. The number 3 is its size.
Summary of the model
- Cost is a function of input size, not a number of seconds.
- Choose
nto match what actually drives the work. - Count the basic operations that dominate the cost.
- State which inputs of size
nyou are counting. - Compare algorithms by how the count grows, because that holds on every machine.
Exercise
The function below takes a list items of length n and a list others of length m. Define the input size(s), then write the number of times the line count += 1 runs as a function of those sizes.
def pairs(items, others):
count = 0
for a in items:
for b in others:
count += 1
return count
Show answer
There are two input sizes: n = len(items) and m = len(others). The outer loop runs n times and the inner loop runs m times for each outer pass, so count += 1 runs n * m times. The cost is a function of both sizes. If both lists have the same length n, it becomes n^2, but you cannot assume that without being told.
Exercise
A student times has_duplicate on a list of 1,000 distinct items and gets 0.04 seconds. Without running anything else, estimate the time for 4,000 distinct items on the same machine, and explain why.
Show answer
The worst-case comparison count is n(n-1)/2, which grows roughly like n^2. Multiplying n by 4 multiplies the count by about 16, so the time is about 16 * 0.04 = 0.64 seconds. Timing noise and caching effects mean the real value will vary, but it should be near this figure.