picamera2 library basics in Raspberry Pi - Time & Space Complexity
When using the picamera2 library, it is helpful to understand how the time to capture and process images grows as you take more pictures or change settings.
We want to know how the program's running time changes when we capture multiple images in a loop.
Analyze the time complexity of the following code snippet.
from picamera2 import Picamera2
picam2 = Picamera2()
picam2.start()
for i in range(n):
image = picam2.capture_array()
# process image here
picam2.stop()
This code starts the camera, captures n images one by one, and then stops the camera.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Capturing an image using
capture_array()inside the loop. - How many times: Exactly
ntimes, once per loop iteration.
Each image capture takes roughly the same time, so total time grows directly with the number of images.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 captures |
| 100 | 100 captures |
| 1000 | 1000 captures |
Pattern observation: Doubling the number of images doubles the total capture time.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the number of images you capture.
[X] Wrong: "Capturing multiple images at once will take the same time as capturing one image."
[OK] Correct: Each image capture takes time, so capturing more images adds up and takes longer overall.
Understanding how loops affect running time helps you explain how programs behave with more data or repeated actions, a key skill in programming and problem solving.
"What if we added image processing inside the loop that takes longer for bigger images? How would the time complexity change?"
