Direction register vs data register in Embedded C - Performance Comparison
We want to understand how the time it takes to set or read pins changes as we work with more pins.
How does using direction registers versus data registers affect the work done by the program?
Analyze the time complexity of the following code snippet.
// Set all pins as output
for (int i = 0; i < n; i++) {
DDR |= (1 << i); // Set direction register bit
}
// Write high to all pins
for (int i = 0; i < n; i++) {
PORT |= (1 << i); // Set data register bit
}
This code sets the direction of n pins to output, then sets each pin high by writing to the data register.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two separate loops each running n times.
- How many times: Each loop runs once for every pin, so n times each.
As the number of pins n increases, the number of operations grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 for direction, 10 for data) |
| 100 | About 200 (100 for direction, 100 for data) |
| 1000 | About 2000 (1000 for direction, 1000 for data) |
Pattern observation: The work doubles as n doubles, showing a steady, linear increase.
Time Complexity: O(n)
This means the time to set directions and write data grows in direct proportion to the number of pins.
[X] Wrong: "Setting all pins at once takes constant time regardless of n."
[OK] Correct: Each pin requires a separate operation in the loop, so time grows with the number of pins.
Understanding how loops over hardware registers scale helps you write efficient embedded code and explain your reasoning clearly.
"What if we set all pins at once using a single write to the register instead of looping? How would the time complexity change?"