Time Functions

One key property we want algorithms to have is to be efficient, i.e. to use the fewest resources possible. This is most commonly considered with respect to time. But how do we work out how long an algorithm takes to run?

In this video I show how to find a time function for an algorithm.

Eleven-minute video

You can also view this video on YouTube


Key Points

  • Each primative operation, like adding two numbers, takes some amount of time
  • By adding up how many of each type of operation we need to perform, we can build up a function that expresses how long an algorithm will take
  • But the actual time will depend on lots of assumptions about the time taken for each primative operation.
  • When adding the time for loops we need to use summations. We’ll see summations in the fourth section in this topic.

Questions

1. Check your understanding

Given the time functions:

  1. T(A) = 6n + 3
  2. T(B) = 3n2 + 2n + 1
  3. T(C) = 3n

Work out T(A), T(B), and T(C) for values of n = 1, 2, 3, 4. Then use your answers to say which the most and least efficient function is for each value of n.

Most efficient
n A B C  
1
2
3
4
Least efficient
n A B C  
1
2
3
4

Check Answers

2. Work out time functions

Work out the time function for the following algorithms written in pseudo-code. Assume each primative operation takes t time. When you’ve got an answer, click “Show answer” to compare with my answer. If we differ slightly in what we’re counting as an operation, that’s okay.

1. Function arrayContains(array : N[], t : N): B
2.     f := false
3.     foreach i in array do
4.         if (i == t)
5.             f := true
5.     end for
6.     return f

Show Answers

1. Procedure reverseArray(a : array [0..n-1] ): N
2.     start := 0
3.     end := length(a)-1
4.     while (start < end) do
5.          tmp := a[start]
6.          a[start] = a[end]
7.          a[end] = tmp
8.          start++
9.          end--
10.    end while

Show Answers


Summary

In this section we saw how time functions can be found for algorithms.

  • You should be able to work out the time function for simple algorithms

Time functions let us analyse how long an algorithm will take, but it requires lots of assumptions that makes it hard to compare different algorithms. In the next section we learn about asymptotic complexity and Big Oh notation, which gives us a way to simplify these time functions to make comparison possible