Enabling and disabling interrupts in Embedded C - Time & Space Complexity
When working with interrupts in embedded C, it's important to understand how enabling and disabling them affects program flow.
We want to see how the time cost changes as the program runs these interrupt control commands.
Analyze the time complexity of the following code snippet.
void critical_section() {
__disable_irq(); // Disable interrupts
// Critical code here
__enable_irq(); // Enable interrupts
}
int main() {
int n = 10; // Example value for n
for (int i = 0; i < n; i++) {
critical_section();
}
}
This code disables interrupts before a critical section and enables them after, repeating this process n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop in
main()callscritical_section()n times. - How many times: The interrupt enable/disable commands run once per loop iteration, so n times total.
Each time the loop runs, it disables and then enables interrupts once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 (10 disables + 10 enables) |
| 100 | 200 (100 disables + 100 enables) |
| 1000 | 2000 (1000 disables + 1000 enables) |
Pattern observation: The number of interrupt control operations grows directly with n.
Time Complexity: O(n)
This means the time spent enabling and disabling interrupts grows in a straight line as the number of loop iterations increases.
[X] Wrong: "Enabling and disabling interrupts inside a loop takes constant time no matter how many times it runs."
[OK] Correct: Each enable/disable call happens every loop iteration, so total time grows with the number of iterations.
Understanding how interrupt control affects program timing helps you write efficient embedded code and explain your reasoning clearly in technical discussions.
"What if we moved the interrupt enable/disable calls outside the loop? How would the time complexity change?"