Polling vs interrupt-driven execution in Embedded C - Performance Comparison
We want to understand how the time cost changes when using polling or interrupts in embedded C programs.
Which method uses more CPU time as input or events increase?
Analyze the time complexity of the following code snippet.
// Polling example
while(1) {
if (data_ready()) {
process_data();
}
}
// Interrupt example
void ISR() {
process_data();
}
This code shows a polling loop checking for data readiness continuously, and an interrupt service routine (ISR) that runs only when data is ready.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: In polling, the loop repeatedly checks data readiness.
- How many times: The check runs continuously, many times even if no data is ready.
- Interrupt-driven: The process_data() runs only when an interrupt occurs, not repeatedly.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Polling: many checks per second; Interrupt: about 10 process_data calls |
| 100 | Polling: still many checks per second; Interrupt: about 100 process_data calls |
| 1000 | Polling: many checks per second; Interrupt: about 1000 process_data calls |
Pattern observation: Polling does many checks regardless of input size, while interrupts run process_data only when needed.
Time Complexity: O(n) for interrupt-driven, O(1) per loop iteration but repeated constantly for polling.
Interrupt-driven execution scales with actual events, polling wastes time checking repeatedly.
[X] Wrong: "Polling is always faster because it checks continuously."
[OK] Correct: Polling wastes CPU time checking even when no data is ready, making it inefficient as input grows.
Understanding how polling and interrupts affect program speed and CPU use is a key skill for embedded programming and real-time systems.
"What if the polling loop included a delay? How would that change the time complexity and CPU usage?"