0
0
Embedded Cprogramming~5 mins

Direction register vs data register in Embedded C - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Direction register vs data register
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of pins n increases, the number of operations grows directly with n.

Input Size (n)Approx. Operations
10About 20 (10 for direction, 10 for data)
100About 200 (100 for direction, 100 for data)
1000About 2000 (1000 for direction, 1000 for data)

Pattern observation: The work doubles as n doubles, showing a steady, linear increase.

Final Time Complexity

Time Complexity: O(n)

This means the time to set directions and write data grows in direct proportion to the number of pins.

Common Mistake

[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.

Interview Connect

Understanding how loops over hardware registers scale helps you write efficient embedded code and explain your reasoning clearly.

Self-Check

"What if we set all pins at once using a single write to the register instead of looping? How would the time complexity change?"