Watching register values in Embedded C - Time & Space Complexity
When watching register values in embedded C, we want to know how the time to check or update these values changes as the program runs.
We ask: How does the number of operations grow when we watch registers repeatedly?
Analyze the time complexity of the following code snippet.
volatile uint8_t *reg = (uint8_t *)0x4000;
void watch_register(int n) {
for (int i = 0; i < n; i++) {
uint8_t val = *reg; // Read register value
// Do something simple with val
}
}
This code reads a hardware register value n times in a loop to watch its changes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading the register value inside the loop.
- How many times: Exactly n times, once per loop iteration.
Each time we increase n, the number of register reads grows the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 register reads |
| 100 | 100 register reads |
| 1000 | 1000 register reads |
Pattern observation: The operations grow directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to watch register values grows linearly with how many times you check it.
[X] Wrong: "Reading a register once or many times takes the same time overall."
[OK] Correct: Each read is a separate operation, so more reads mean more time spent.
Understanding how loops affect time helps you explain how embedded systems handle hardware efficiently.
"What if we added a nested loop to watch multiple registers each time? How would the time complexity change?"