Memory-mapped I/O concept in Embedded C - Time & Space Complexity
When using memory-mapped I/O, we want to know how the time to access hardware changes as we do more operations.
We ask: How does the number of hardware reads or writes grow with the number of commands?
Analyze the time complexity of the following code snippet.
#define IO_REG (*(volatile unsigned int*)0x40000000)
void write_values(int* values, int n) {
for (int i = 0; i < n; i++) {
IO_REG = values[i];
}
}
This code writes a list of values to a hardware register using memory-mapped I/O.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing a value to the hardware register.
- How many times: Once for each value in the input array, so n times.
Each new value adds one more write to the hardware register.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The number of operations grows directly with the number of values.
Time Complexity: O(n)
This means the time to write values grows in a straight line as you add more values.
[X] Wrong: "Writing to a hardware register is instant and does not add to time."
[OK] Correct: Each write takes time because it communicates with hardware, so more writes mean more time.
Understanding how hardware access scales helps you design efficient embedded programs and shows you know how software and hardware work together.
"What if we buffered values and wrote them in batches? How would the time complexity change?"