Reading a hardware register in Embedded C - Time & Space Complexity
When reading a hardware register, we want to know how the time to read changes as we do more reads.
We ask: How does the work grow if we read the register many times?
Analyze the time complexity of the following code snippet.
volatile uint32_t *REG = (uint32_t *)0x40000000;
uint32_t read_value;
for (int i = 0; i < n; i++) {
read_value = *REG;
}
This code reads a hardware register at a fixed address n times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading the hardware register once per loop.
- How many times: The read happens
ntimes, once each loop cycle.
Each time we increase n, the number of reads grows the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads |
| 100 | 100 reads |
| 1000 | 1000 reads |
Pattern observation: The work grows directly with n. Double n, double the reads.
Time Complexity: O(n)
This means the time to complete grows in a straight line as you read more times.
[X] Wrong: "Reading a hardware register is instant and does not add time."
[OK] Correct: Each read takes some time, so doing many reads adds up and grows with n.
Understanding how repeated hardware reads affect time helps you reason about performance in embedded systems.
"What if we added a delay inside the loop after each read? How would the time complexity change?"