0
0
Arduinoprogramming~5 mins

Why interrupts improve responsiveness in Arduino - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why interrupts improve responsiveness
O(n)
Understanding Time Complexity

We want to see how using interrupts changes how fast a program reacts to events.

How does the program's work grow when it waits for things to happen?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


volatile bool flag = false;

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), isr, RISING);
}

void loop() {
  if (flag) {
    // handle event
    flag = false;
  }
}

void isr() {
  flag = true;
}
    

This code uses an interrupt to set a flag when a signal changes, so the main loop can respond quickly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The main loop runs repeatedly checking the flag.
  • How many times: The loop runs continuously, but the interrupt runs only when the event happens.
How Execution Grows With Input

Execution mainly depends on how often the interrupt triggers, not on input size.

Input Size (n)Approx. Operations
10 eventsLoop runs many times, interrupt runs 10 times
100 eventsLoop runs many times, interrupt runs 100 times
1000 eventsLoop runs many times, interrupt runs 1000 times

Pattern observation: The interrupt handling grows linearly with the number of events, but the loop runs continuously regardless.

Final Time Complexity

Time Complexity: O(n)

This means the work done to handle events grows directly with how many events happen.

Common Mistake

[X] Wrong: "Interrupts make the program run faster all the time."

[OK] Correct: Interrupts help respond quickly to events, but the main loop still runs continuously and uses time.

Interview Connect

Understanding how interrupts affect program responsiveness shows you can write code that reacts well to real-world signals, a useful skill in many projects.

Self-Check

"What if we replaced the interrupt with a simple polling check inside the loop? How would the time complexity and responsiveness change?"