CSC 288 · Structured Programming
Our notes
2 min readMeasuring efficiency
Time on a stopwatch depends on the computer, so we count the basic operations a program performs as the input size n grows, and describe the growth with big-O notation.
Common growth rates
| Big-O | Name | Example |
|---|---|---|
| O(1) | constant | reach a[k] |
| O(log n) | logarithmic | binary search |
| O(n) | linear | linear search, summing an array |
| O(n log n) | linearithmic | merge sort, quicksort on average |
| O(n²) | quadratic | selection sort, comparing all pairs |
| O(2ⁿ) | exponential | trying every subset |
Worked example: how growth matters
Suppose one operation takes 1 microsecond. For n = 1,000,000:
- O(log n): about 20 operations, 20 µs.
- O(n): 1 s.
- O(n log n): about 20,000,000, 20 s.
- O(n²): 10¹², about 11.6 days.
A better algorithm beats a faster computer.
Finding the order of a loop
- One loop over n items: O(n).
- A loop inside a loop, both over n: O(n²).
- A loop that halves its range each time: O(log n).
Example: for i := 1 to n do for j := i to n do ... runs n + (n − 1) + ... + 1 = n(n + 1)/2 times: O(n²).
Practical speed-ups
- Choose the right algorithm and data structure (binary search instead of linear on sorted data; a tree or hash table for frequent lookups).
- Move unchanging work out of loops: compute length(s) or a constant expression once.
- Avoid repeated work: store results you will need again.
- Pass large arrays as var or const parameters to avoid copying.
- Use integer arithmetic where reals are not needed.
- Read files in large pieces, not character by character.
- Measure before optimising: find the part that really takes the time (a profiler, or timing statements).
Clarity first
Most of a program's time is spent in a small part of its code. Write clearly first, then improve only the slow parts. "Premature optimisation is the root of all evil" (Knuth, 1974).
Exams usually ask
- Explain big-O notation and order common algorithms by efficiency.
- Find the order of a given loop or nested loops.
- Suggest ways to make a given program more efficient.
Common mistake
Comparing algorithms by timing them once on a small input. On 10 items everything is fast; the growth rate shows on large inputs.
Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.
No reading links here yet
Our team adds free books, videos and practice for each topic, and opens every link before it goes up.