0
0
Arduinoprogramming~5 mins

attachInterrupt() function in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: attachInterrupt() function
O(n)
Understanding Time Complexity

When using the attachInterrupt() function, it's important to understand how often the interrupt code runs as input changes.

We want to know how the time spent in the interrupt grows as events happen.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


volatile int count = 0;

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), countPulse, RISING);
}

void countPulse() {
  count++;
}

void loop() {
  // main code runs here
}
    

This code counts how many times a signal rises on pin 2 using an interrupt.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The interrupt service routine countPulse() runs each time the signal rises.
  • How many times: It runs once per rising signal event, which depends on external input frequency.
How Execution Grows With Input

The time spent in countPulse() grows directly with the number of rising signals detected.

Input Size (number of rising signals)Approx. Operations (interrupt calls)
1010 calls to countPulse()
100100 calls to countPulse()
10001000 calls to countPulse()

Pattern observation: The number of interrupt calls grows linearly with the number of signal events.

Final Time Complexity

Time Complexity: O(n)

This means the total time spent in the interrupt grows directly with the number of signal events.

Common Mistake

[X] Wrong: "The interrupt runs constantly and uses the same time no matter how many signals come."

[OK] Correct: The interrupt only runs when a signal event happens, so more events mean more interrupt calls and more time spent.

Interview Connect

Understanding how interrupts affect program timing helps you write responsive and efficient code in real projects.

Self-Check

What if the interrupt routine did more work inside? How would that affect the time complexity?