0
0
Embedded Cprogramming~5 mins

Enabling and disabling interrupts in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Enabling and disabling interrupts
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop in main() calls critical_section() n times.
  • How many times: The interrupt enable/disable commands run once per loop iteration, so n times total.
How Execution Grows With Input

Each time the loop runs, it disables and then enables interrupts once.

Input Size (n)Approx. Operations
1020 (10 disables + 10 enables)
100200 (100 disables + 100 enables)
10002000 (1000 disables + 1000 enables)

Pattern observation: The number of interrupt control operations grows directly with n.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how interrupt control affects program timing helps you write efficient embedded code and explain your reasoning clearly in technical discussions.

Self-Check

"What if we moved the interrupt enable/disable calls outside the loop? How would the time complexity change?"