Time-lapse photography in Raspberry Pi - Time & Space Complexity
When creating a time-lapse, the program takes many photos over time. We want to understand how the time to complete the task grows as we take more photos.
How does the number of photos affect the total running time?
Analyze the time complexity of the following code snippet.
import time
from picamera import PiCamera
camera = PiCamera()
for i in range(num_photos):
camera.capture(f'image_{i}.jpg')
time.sleep(interval_seconds)
This code takes a set number of photos, waiting a fixed time between each shot.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Taking a photo with
camera.capture()inside the loop. - How many times: Exactly
num_photostimes, once per loop iteration.
Each photo adds one capture operation and one wait period, so total time grows directly with the number of photos.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 captures + 10 waits |
| 100 | 100 captures + 100 waits |
| 1000 | 1000 captures + 1000 waits |
Pattern observation: Doubling the number of photos doubles the total work and time.
Time Complexity: O(n)
This means the total time grows in a straight line as you take more photos.
[X] Wrong: "Taking more photos only adds a little extra time, so it's almost constant."
[OK] Correct: Each photo requires a full capture and wait, so time adds up directly with the number of photos.
Understanding how loops affect time helps you explain how programs scale, a key skill in many coding tasks.
"What if we removed the wait time between photos? How would the time complexity change?"
