ISR best practices (keep it short) in Embedded C - Time & Space Complexity
We look at how the time an Interrupt Service Routine (ISR) takes grows with input or events.
We want to know how fast the ISR runs as more interrupts happen.
Analyze the time complexity of this simple ISR example.
void ISR_Handler(void) {
static int count = 0;
count++;
if (count >= 100) {
count = 0;
// Do a quick task
}
}
This ISR increments a counter each time it runs and does a quick task every 100 interrupts.
Look for repeated actions inside the ISR.
- Primary operation: Incrementing the counter and checking its value.
- How many times: Once per interrupt event.
The ISR runs once for each interrupt, doing a small fixed task.
| Interrupts (n) | Approx. Operations |
|---|---|
| 10 | 10 increments and checks |
| 100 | 100 increments and checks, 1 quick task |
| 1000 | 1000 increments and checks, 10 quick tasks |
Pattern observation: The work grows directly with the number of interrupts.
Time Complexity: O(n)
This means the total ISR work grows linearly with the number of interrupts.
[X] Wrong: "The ISR time stays the same no matter how many interrupts happen."
[OK] Correct: Each interrupt triggers the ISR, so total work adds up with more interrupts.
Understanding ISR time helps you write fast, reliable embedded code that handles events smoothly.
"What if the ISR called a function that loops over an array of size n? How would the time complexity change?"