PWMLED for brightness in Raspberry Pi - Time & Space Complexity
We want to understand how the time it takes to change LED brightness grows as we adjust the brightness steps.
How does the number of brightness changes affect the total time spent?
Analyze the time complexity of the following code snippet.
from gpiozero import PWMLED
from time import sleep
led = PWMLED(17)
for brightness in range(0, 101):
led.value = brightness / 100
sleep(0.01)
This code gradually increases the LED brightness from off to full brightness in 101 steps, pausing briefly between each step.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that sets the LED brightness 101 times.
- How many times: Once for each brightness level from 0 to 100 (101 times).
As the number of brightness steps increases, the total time grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 brightness changes |
| 100 | 100 brightness changes |
| 1000 | 1000 brightness changes |
Pattern observation: Doubling the number of brightness steps doubles the total operations and time.
Time Complexity: O(n)
This means the time to complete the brightness changes grows linearly with the number of steps.
[X] Wrong: "Changing brightness a few more times won't affect the total time much."
[OK] Correct: Each brightness change takes time, so more steps add up and increase total time proportionally.
Understanding how loops affect time helps you explain how your code scales when controlling hardware like LEDs.
"What if we changed the sleep time to zero? How would the time complexity change?"