Computational Complexity
In questa pagina 9
An algorithma finite and unambiguous sequence of instructions that, starting from a set of input data, solves a problem in a finite number of steps usually has many alternatives for the same problem: how can we tell that one is "better" than another? For many centuries the study of algorithms focused on correctness. With electronic computers it became evident that correctness is not enough: a correct but too slow algorithm, or one too expensive in memory, can be unusable in practice. Hence the need to analyse algorithms quantitatively. The analysis of algorithms was systematised in the 1960s by Donald Knuth; the theory of computational complexity (the time and memory intrinsically required to solve a problem, whatever the algorithm) dates from 1965. The symbols , , come from number theory (Bachmann 1894, Landau) and were adopted for algorithms by Knuth. Which problems can be solved efficiently (for instance the open question "P versus NP") is still a subject of research.
1. Why analyse algorithms
Analysis allows us to
- make performance predictions on inputs never processed before, without having to run them;
- compare different algorithmic solutions of the same problem and consciously choose the most suitable one for the case at hand.
Two complementary types of analysis exist:
- experimental: implement the algorithm and measure its behaviour;
- theoretical: reason about the algorithm "on paper", without executing it.
Resources that can be studied:
| resource | name |
|---|---|
| execution time | time complexity |
| amount of memory occupied | space complexity |
We focus mainly on execution time, the most critical resource.
2. Experimental analysis
To evaluate the time efficiency of an implementation we measure the execution time on datasets of different sizes. This measures the scalability of the implementation with respect to the input size.
Running example: reverse returns a reversed copy of a list (last element first, and so on). This is an ineffective implementation, as we shall see.
def reverse(my_list):
# Prepare space for the output list,
# and treat it as a partially filled list
n = len(my_list)
output = [0] * n
# the number of elements inserted in `output` so far
output_size = 0
# For each element of the input, insert it
# _at the beginning_ of the "output" list, taking
# care to shift all previously inserted elements
# by one position, to make room.
for i in range(n):
# make room by shifting all elements
for j in range(output_size, 0, -1):
output[j] = output[j - 1]
# write the element at the beginning of the output list
output[0] = my_list[i]
# increase the logical size
output_size += 1
return outputAt each iteration of the outer loop all elements already in output are shifted one position to the right (this is the inner loop for j in range(output_size, 0, -1)), then my_list[i] is written at position 0.
Measuring time
time.time() from the time module returns the number of seconds elapsed since the UNIX epoch (midnight of January 1st, 1970). It returns an instant (a timestamp): a duration is the difference between two timestamps.
import time
# run the algorithm and measure execution time
start = time.time()
reverse(my_list)
end = time.time()
elapsed = end - startFor a scalability experiment inputs of increasing length are used; to cover a wide range of sizes with few experiments, the size doubles at each experiment. Results are written as CSVComma Separated Values: one record per line, fields separated by a comma, easy to import in other software such as Excel: input size, comma, time.
import time
# Try different sizes, in increasing order
for i in range(1, 11):
# The size of the list
n = 2 ** i * 1000
# The list to reverse, the content doesn't matter
my_list = [0] * n
# run the algorithm and measure execution time
start = time.time()
reverse(my_list)
end = time.time()
# Write to output the problem size
# and the execution time (in seconds)
with open("times.csv", "a") as file:
print(str(n) + "," + str(end - start), file=file)Measured times of the quadratic reverse (size, seconds):
| size | time (s) |
|---|---|
| 2000 | 0.0526 |
| 4000 | 0.2352 |
| 8000 | 0.9751 |
| 16000 | 4.0043 |
| 32000 | 16.4047 |
Estimating the exponent
When the size doubles, the time tends to quadruple. If the relation were linear the time would simply double, so the relation is non-linear, governed by a polynomial of higher degree. To make it quantitative, suppose the time on an instance of size is
with and constants to determine ( is the exponent we want). In the ratio of two consecutive measurements ( and ) the constant cancels:
With the data: , so the trend is approximated by .
Why doubling the size is convenient: it covers a very wide range of values with few measurements, and the ratio between consecutive trials directly reveals the exponent.
Limits of the experimental analysis
The measured time is influenced by many factors:
- the content of the input (integers, strings, lists, ...);
- the characteristics of the hardware;
- the programming language used;
- the interpreter or compiler used;
- the quality of the code.
So we measure the properties of an implementation of the algorithm, not of the algorithm itself. To reason about the algorithm we need the tools of theoretical analysis.
3. Theoretical analysis: the cost model
Theoretical analysis is qualitative and based on counting the fundamental operations an algorithm performs. It lets us predict performance before implementing, and compare algorithms for the same problem by grouping them into complexity classes.
Key assumption: the running time is proportional to the number of machine instructions executed. Counting exact machine instructions from the code is impractical, so we adopt simplifying assumptions: the cost model.
We assume the execution time depends on: the number of primitive operations (basic steps), the size of the data, the value of the data.
Basic steps are operations with constant execution time, independent of the number, type and value of the data:
| operation | example |
|---|---|
| assigning a value to a variable | a = 5 |
| arithmetic operations | b = a + 5 |
| logical and comparison operations | isX = b1 and b2, b1 = a > 5 |
| read or write access to a cell of a list | value = my_list[k] |
Warnings:
- a function call is not a primitive operation, since the function may not take constant time.
len(my_list)on an already known list has constant cost, butreversetakes a time that grows with the input size: in the count the call must be replaced by the actual cost of the function's execution; - the steps considered basic depend on the context. For sorting algorithms only the read and write list accesses are counted as basic steps and all other operations (arithmetic, ...) are given zero cost, because the number of list accesses is a good approximation of the overall work and simplifies the analysis.
4. Asymptotic notations
In theoretical analysis we care about the qualitative trend of performance, in particular for large inputs. We characterise an algorithm with functions (domain: the natural numbers) and define three sets of functions.
- Big (upper bound). if there exist constants and such that for every : .
- Big (lower bound). if there exist and such that for every : .
- Big (lower and upper bound). if there exist , and such that for every : .
Intuitively: means grows at most as fast as ; means at least as fast; means exactly as fast (neither faster nor slower), up to a multiplicative constant.
- The constants , , let us ignore multiplicative factors.
- The threshold lets us neglect the behaviour for small inputs, looking only at the trend for large ones.
In the graphs of the course: for , stays below for (even if above it for smaller ); for it stays above ; for it stays between and .
Equivalently, if and only if and : the "exact" characterisation of is the combination of an upper and a lower bound. In practice one often finds written instead of : a well-established abuse of notation, since is a set of functions and the "equal" sign must be understood as membership.
Growth rates
Typical classes compared in the course, for the number of operations as the input size grows (, , , , ):
Grafico interattivo
Examples
Only the fastest-growing term decides the class; constant factors and lower-order terms are absorbed.
The upper bound of is not necessarily tight: . Likewise the lower bound of : . The characterisation is always tight: .
Relation with limits
Let .
- If then . Proof: by the definition of limit, for every there is such that for all : . Choose (valid because ). Then for all : . Since , multiplying by : . This is exactly the definition of with and .
- If then (sketch): take ; for , , so and works. (Actually , which is stronger: it holds for every .)
- If then (sketch): by the definition of infinite limit, for there is such that for , so and works.
5. Deriving the complexity from code
Rules to derive the complexity from pseudocode or code:
- blocks without loops or decisions: count the basic operations;
- two blocks executed alternatively (the two branches of an
if): take the number of operations of the branch that executes more when deriving an upper bound, the number of the branch that executes fewer when deriving a lower bound; - loops: sum the number of operations performed at each iteration.
(Sequential blocks: the operations of the components are summed.)
Example: the quadratic reverse
Block before the loops
n = len(my_list)
output = [0] * n
output_size = 0- 2 operations for the first line (call to
lenand writing ofn); - operations to initialise the list
output; - 1 operation to initialise
output_size;
total .
Body of the innermost loop: output[j] = output[j - 1]: one arithmetic operation (), one read access, one write access: 3 operations, constant (it does not depend on the input size).
How many times does the inner loop run? Throughout the function output_size == i holds, so in iteration of the outer loop the inner body is executed times: the inner loop costs .
Body of the outer loop (per iteration ): for the inner loop, plus a read access to my_list and a write access to output (for output[0] = my_list[i]), plus the increment output_size += 1. The course counts this as operations. The outer loop runs times, so, including the initial block, the total is
using the Gauss sum formula
(the course material prints for the linear term; the arithmetic gives , which does not change the class). The algorithm is therefore . By the properties of asymptotic notation the precise count of constant operations is irrelevant: it is enough to identify the terms that grow fastest as increases, the only ones that determine the complexity class.
Proof of the Gauss formula.
- Arithmetic proof: write the sum twice, the second time in reverse order, and add column by column: for each of the columns (pairs and , and , ..., and ). So , hence .
- Geometric proof: two staircases of squares fit together into a rectangle , which has squares.
Agreement with the experiment. Experimentally, doubling the input made the time quadruple (); the derived explains it exactly: doubling multiplies the time by . The two analyses, from different premises, reach the same conclusion and reinforce each other.
6. A linear algorithm for reverse
The inefficiency of the first version comes from inserting each new element at the beginning of output, which forces shifting all elements already present: this "hidden work" in the inner loop makes it quadratic. Idea: visit the input list from the end and write the elements into output starting from the first position, so each element goes directly into its final position, without moving anything.
def reverse(my_list):
# Prepare space for the output list
n = len(my_list)
output = [0] * n
# Visit the input list starting from the last
# element (index n - 1) down to the first (index 0),
# copying each element into `output` starting from
# the first position onward.
for i in range(n):
output[i] = my_list[n - 1 - i]
return outputFor i = 0 it writes the last input element into output[0], for i = 1 the second to last into output[1], and so on until output[n - 1] receives the first input element.
Theoretical analysis
- block before the loop: 2 operations for the first line plus for the initialisation of
output: ; - loop body
output[i] = my_list[n - 1 - i]: a constant number of arithmetic operations for the index (two subtractions), one read access, one write access: a constant (here ); - there is no inner loop: the body has no operations that depend on . The loop runs times, so
The algorithm is linear.
Experimental check (same method, sizes doubling): the times now tend to double, not quadruple.
| size | time (s) |
|---|---|
| 2000 | 0.000091 |
| 4000 | 0.000151 |
| 8000 | 0.000318 |
| 16000 | 0.000621 |
| 32000 | 0.001281 |
, in agreement with .
7. Comparing the two algorithms
They solve exactly the same problem with the same result, but with radically different performance:
| size | (s) | (s) | ratio |
|---|---|---|---|
| 2000 | 0.053 | 0.000091 | about 580 |
| 4000 | 0.235 | 0.000151 | about 1560 |
| 8000 | 0.975 | 0.000318 | about 3070 |
| 16000 | 4.004 | 0.000621 | about 6440 |
| 32000 | 16.405 | 0.001281 | about 12800 |
Two observations:
- the linear algorithm is faster: already for it is more than ten thousand times faster;
- more important, the gap grows with the input size, from about 580 to about 12800. This is what we expect from the classes: since , the ratio between the two times grows linearly with the input size.
The choice of the algorithm (and thus of its complexity class) has an impact on performance that no improvement in hardware or programming language could ever compensate for, for sufficiently large inputs. The real difference lies in the asymptotic behaviour, not in the speed on a single input. A faster computer only reduces times by a constant factor, it does not change the order of growth.
8. Worked checks (review questions of the course)
- Exponent from two times. s and s: , so the algorithm is presumably (cubic).
- Nested loops.
total = 0
for i in range(n):
for j in range(n):
total = total + 1The innermost instruction runs times with constant cost: .
total = 0
for i in range(n):
for j in range(i):
total = total + 1At iteration () the inner loop runs times, so in total times. The inner loop is shorter on average than before, but the complexity is still .
- True or false?
- : true (the dominant term is , the lower-order term is absorbed).
- : true ( for ; the upper bound need not be tight).
- : false ( but not : it grows strictly faster).
- : true (the exponential dominates any polynomial term).
- : false (it would need eventually, i.e. , impossible for large ).
- : true (take ; in fact ).
- Why constants do not matter: asymptotic notation absorbs constant multiplicative factors and lower-order terms; only the fastest-growing term determines the class, and a constant contribution does not change the order of growth.
See RecursionA function is recursive when it calls itself; it is correct only if it has at least one base case that needs no recursive call and if every recursive call works on a simpler problem that gets closer to a base case (otherwise Python stops with RecursionError, the limit being 1000 nested calls). Each pending call is a record on the call stack. Types: linear (one call, e.g. factorial), binary (two calls, e.g. sum of a list by halves), tail (the call is the last action, solved with an accumulator and easy to turn into a loop), multiple (fib_bad recomputes the same values and explodes). Typical examples: factorial, Fibonacci, reversing a string, Towers of Hanoi (2^n - 1 moves). Recursion is elegant for naturally recursive problems but usually less efficient than a loop.Recursion → for algorithms whose cost is not a simple loop count (for example the doubly recursive Fibonacci).
Typical mistakes
- Treating a function call as one basic step: its real cost must be counted (
lenon a known list is constant,reverseis not). - Reading and as part of the algorithm: they only serve to ignore small inputs and multiplicative constants.
- Confusing with : is true but not tight, while .
- Concluding from one measurement: times depend on hardware, language, interpreter and input, so experiments measure an implementation; the exponent is estimated from the ratio over increasing sizes.
- For an
if, using the wrong branch: the longer branch for an upper bound, the shorter one for a lower bound.
Versione ripasso
Why. Correctness is not enough: time and memory decide whether an algorithm is usable. Analysis predicts performance on unseen inputs and compares solutions. Focus: time complexity (also space).
Experimental analysis.
- Time with
time.time(): the difference of two timestamps, in seconds. - Double the input size at each run (
n = 2 ** i * 1000) and writesize,timelines to a CSV file. - If , then . Quadratic
reverse: time about x4 when the size doubles, so . - It measures an implementation (hardware, language, interpreter, input content), not the algorithm.
Theoretical analysis. Count basic steps under a cost model: assignment, arithmetic, logical and comparison operations, read or write of a list cell (constant time). A function call is not a basic step: count its real cost. For sorting, only list accesses are counted.
Asymptotic notation (for on the naturals, constants , ):
- , upper bound: for .
- , lower bound: for .
- , both: ; equivalent to and together.
- Constants and lower-order terms are absorbed: .
- need not be tight: , but .
- Growth order to remember: , , , .
Limits. With : if then (with , ); if then (in fact ); if then .
Deriving complexity from code.
- Basic blocks: count the operations; sequential blocks: sum them.
if: the longer branch for an upper bound, the shorter for a lower bound.- Loops: sum the operations of each iteration. Nested
for i in range(n)/for j in range(n)gives ; withrange(i)the inner count is , still .
Worked example: quadratic reverse (each element inserted at the front, shifting the others). At iteration the inner loop runs times, cost ; the outer body costs . Total:
using (the course prints for the linear term; the class is unchanged).
Linear version: write each element directly into its final place, output[i] = my_list[n - 1 - i]; no inner loop, cost . Experimentally the times double.
Comparison. At : 16.405 s against 0.001281 s, a ratio of about 12800; the gap grows linearly with . No faster hardware compensates a worse class for large inputs.
Checks. s and s give , so . is true; is false; is true; is false.
Common mistakes: counting a function call as one step; reading and as part of the algorithm; confusing with ; concluding from one measurement; taking the wrong branch of an if.