Reading history

Analysis of Algorithms: Measuring Time and Space

6 min read 5 views

Learn to analyse an algorithm before you code it: counting steps, input size, growth rates, and the time and space trade-offs that pick the winner.

Analysis of algorithms is how programmers predict whether a solution will be fast enough before they spend hours writing it. Instead of timing code on one computer, you count how many basic steps it takes as the input grows. Two solutions that look equally good on ten items can differ by a factor of fifty thousand on a hundred thousand.

In this lesson you will learn

  • Why we analyse algorithms instead of just timing them
  • What counts as a “step” and what “input size” means
  • How to compare two solutions to the same problem
  • The trade-off between time and memory
  • The mistakes beginners make when analysing code

Why Analyse an Algorithm Before Coding?

Timing a program with a stopwatch seems simpler, but the result depends on the computer, the compiler, what else is running and, above all, on the test data. A program that finishes instantly on your 20-line test file may take hours on the real 2-million-line file.

Analysis answers a better question: how does the amount of work grow as the input grows? That answer does not depend on hardware, and you can work it out on paper before writing any code. It tells you:

  • whether an idea is fast enough for the input sizes you expect;
  • which of two working solutions to choose;
  • where the slow part of a program is.

Counting Steps and Measuring Input Size

A step is any basic operation that takes a fixed amount of time: an addition, a comparison, an assignment, reading a[i]. The input size, written n, is whatever measures how big the problem is: the number of items in an array, the number of characters in a string, the number of vertices in a graph.

Consider adding the numbers 1 to n. A loop does one addition per number. Gauss’s formula, n(n + 1)/2, does the same job with three operations whatever n is.

#include <stdio.h>

/* Sum 1..n: a loop does n additions; Gauss's formula does 3 operations. */
int main(void) {
    long n = 1000000;
    long loop_sum = 0, steps = 0;
    for (long i = 1; i <= n; i++) { loop_sum += i; steps++; }
    long formula = n * (n + 1) / 2;
    printf("loop:    %ld after %ld additions\n", loop_sum, steps);
    printf("formula: %ld after 3 operations\n", formula);
    return 0;
}

Output

loop:    500000500000 after 1000000 additions
formula: 500000500000 after 3 operations

The loop’s work grows in step with n; the formula’s work does not grow at all. In the notation used throughout this course, the loop is O(n) and the formula is O(1). Big O is introduced properly in Big O notation.

We usually look at the worst case: the input of size n that makes the algorithm work hardest. That gives a guarantee. Other cases are covered in worst, average and best case analysis.

Comparing Two Solutions to One Problem in C

Problem: does a list of roll numbers (each between 0 and 99,999) contain a duplicate?

  • Solution A compares every pair of numbers.
  • Solution B keeps a table of numbers already seen and checks each new number against it in one step.

The program counts the steps each makes when there is no duplicate, which is the worst case for both.

#include <stdio.h>

/* Two ways to answer "is there a duplicate roll number?" Count the comparisons. */
static long pairs_check(const int a[], int n) {
    long steps = 0;
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) { steps++; if (a[i] == a[j]) return steps; }
    return steps;
}

static long seen_check(const int a[], int n) {     /* roll numbers are 0..99999 */
    static char seen[100000];
    long steps = 0;
    for (int i = 0; i < 100000; i++) seen[i] = 0;
    for (int i = 0; i < n; i++) { steps++; if (seen[a[i]]) return steps; seen[a[i]] = 1; }
    return steps;
}

int main(void) {
    static int rolls[100000];
    for (int n = 10; n <= 100000; n *= 10) {
        for (int i = 0; i < n; i++) rolls[i] = i;   /* no duplicates: worst case */
        printf("n = %6d   pairs: %11ld steps   seen-table: %6ld steps\n",
               n, pairs_check(rolls, n), seen_check(rolls, n));
    }
    return 0;
}

Output

n =     10   pairs:          45 steps   seen-table:     10 steps
n =    100   pairs:        4950 steps   seen-table:    100 steps
n =   1000   pairs:      499500 steps   seen-table:   1000 steps
n =  10000   pairs:    49995000 steps   seen-table:  10000 steps
n = 100000   pairs:  4999950000 steps   seen-table: 100000 steps

For 10 numbers, both are instant. For 100,000 numbers, Solution A does about 5 billion comparisons while Solution B does 100,000 checks: 50,000 times less work. Solution A’s steps follow n(n − 1)/2, which grows like n². Solution B’s steps equal n.

Solution B is not free, though. It uses an extra table of 100,000 bytes, whatever the input size. This is a common pattern called the time-memory trade-off: spending memory to save time. Analysis lets you see both costs clearly. Memory cost is covered in space complexity.

How Growth Rates Compare

nlog₂nnn log₂nn²2n
10310331001,024
100710066410,000about 1030
1,000101,0009,9661,000,000far too many
1,000,000201,000,000about 20 million1012far too many

A rough guide: a computer does around 100 million simple steps per second. So an n² algorithm is fine for 1,000 items but takes hours for a million, while n log n handles a million in a fraction of a second.

Analysis Mistakes Beginners Make

  1. Judging by tiny tests. Every algorithm is fast on 10 items. Always ask what happens at the real input size.
  2. Counting lines instead of steps. One line can hide a loop, such as strlen(s) or a call to a sorting function.
  3. Ignoring the worst case. A search that is usually quick but sometimes scans everything will, sooner or later, scan everything.
  4. Caring about constants too early. Saving one step per loop matters far less than changing n² to n.
  5. Forgetting memory. A fast algorithm that needs more memory than the machine has will not run at all.

Practice Exercises

Exercise 1. A program checks every pair in a list of 2,000 names. Roughly how many comparisons is that?

Show answer

2,000 × 1,999 / 2 = 1,999,000, about 2 million.

Exercise 2. Algorithm X takes n² steps and algorithm Y takes 1,000n steps. Which is faster for n = 500? For n = 5,000?

Show answer

For n = 500, X takes 250,000 steps and Y takes 500,000, so X is faster. For n = 5,000, X takes 25 million and Y takes 5 million, so Y is faster. The faster-growing algorithm always loses once n is large enough.

Exercise 3. In the duplicate checker, what would make Solution B unusable?

Show answer

If the values could be huge, such as any 64-bit number, a table with one slot per possible value would be impossibly large. A hash table or sorting would be needed instead.

Frequently Asked Questions

Is analysis of algorithms the same as Big O?

Big O is the notation used to write down the result. Analysis is the process of counting the steps and finding how they grow.

Do I still need to time my programs?

Yes. Analysis picks the right algorithm; timing and profiling then tune the real code on real hardware.

What should I study next?

Learn how growth rates are ranked in order of growth, then work through asymptotic analysis.

What to Remember About Algorithm Analysis

  • Analysis counts basic steps as a function of input size n, not seconds.
  • Look at how the step count grows, usually in the worst case.
  • An n² solution and an n solution can differ by thousands of times on real data.
  • Faster algorithms often use more memory: weigh both.
  • Analyse first, then code and measure.
Lessons are also marked complete when you click Next.