0
0
Raspberry Piprogramming~5 mins

PWMLED for brightness in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: PWMLED for brightness
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the number of brightness steps increases, the total time grows in direct proportion.

Input Size (n)Approx. Operations
1010 brightness changes
100100 brightness changes
10001000 brightness changes

Pattern observation: Doubling the number of brightness steps doubles the total operations and time.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the brightness changes grows linearly with the number of steps.

Common Mistake

[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.

Interview Connect

Understanding how loops affect time helps you explain how your code scales when controlling hardware like LEDs.

Self-Check

"What if we changed the sleep time to zero? How would the time complexity change?"