Writing an ISR (Interrupt Service Routine) in Embedded C - Time & Space Complexity
When writing an ISR, it's important to know how long it takes to run as input changes.
We want to see how the ISR's work grows when it handles more data or events.
Analyze the time complexity of the following code snippet.
volatile int data_ready = 0;
int buffer[100];
int index = 0;
void ISR_Handler() {
if (data_ready) {
buffer[index++] = read_sensor();
if (index >= 100) {
index = 0;
}
data_ready = 0;
}
}
This ISR reads sensor data when ready and stores it in a buffer, resetting when full.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading sensor data and storing it once per interrupt.
- How many times: Once each time the interrupt triggers, no loops inside ISR.
The ISR does a fixed amount of work each time it runs, no matter how many times it has run before.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 interrupts | 10 sensor reads and stores |
| 100 interrupts | 100 sensor reads and stores |
| 1000 interrupts | 1000 sensor reads and stores |
Pattern observation: Each interrupt causes a fixed small task, so work grows directly with number of interrupts.
Time Complexity: O(1)
This means the ISR runs in constant time each time it is called, regardless of input size.
[X] Wrong: "The ISR time grows with how many times it has run before because the buffer fills up."
[OK] Correct: The ISR only does a fixed set of steps each call; it does not loop over the whole buffer.
Understanding ISR time helps you write fast, reliable embedded code that keeps systems responsive.
"What if the ISR had a loop to process all buffer elements each time? How would the time complexity change?"