Why interrupts improve responsiveness in Arduino - Performance Analysis
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?
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 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.
Execution mainly depends on how often the interrupt triggers, not on input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 events | Loop runs many times, interrupt runs 10 times |
| 100 events | Loop runs many times, interrupt runs 100 times |
| 1000 events | Loop 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.
Time Complexity: O(n)
This means the work done to handle events grows directly with how many events happen.
[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.
Understanding how interrupts affect program responsiveness shows you can write code that reacts well to real-world signals, a useful skill in many projects.
"What if we replaced the interrupt with a simple polling check inside the loop? How would the time complexity and responsiveness change?"