Writing to a hardware register in Embedded C - Time & Space Complexity
When writing to a hardware register, it's important to know how the time needed changes as the program runs.
We want to see how the number of write operations grows with the input size.
Analyze the time complexity of the following code snippet.
volatile uint32_t *REG = (volatile uint32_t *)0x40021000;
void write_values(uint32_t *values, int n) {
for (int i = 0; i < n; i++) {
*REG = values[i];
}
}
This code writes each value from an array to a hardware register one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing a value to the hardware register inside the loop.
- How many times: Exactly once for each element in the input array, so n times.
Each new value in the input array causes one write operation to the register.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The number of writes grows directly with the number of input values.
Time Complexity: O(n)
This means the time to complete writing grows in direct proportion to the number of values.
[X] Wrong: "Writing to a hardware register is always constant time no matter how many values."
[OK] Correct: Each write operation takes time, so writing multiple values adds up linearly.
Understanding how loops affect time helps you explain how embedded code interacts with hardware efficiently.
"What if we added a nested loop writing the same values multiple times? How would the time complexity change?"