0
0
Verilogprogramming~5 mins

Up-down counter with direction control in Verilog - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Up-down counter with direction control
O(n)
Understanding Time Complexity

We want to understand how the time needed to run an up-down counter changes as the input size changes.

Specifically, how does the counting process scale when we control the direction?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

module up_down_counter(
  input wire clk,
  input wire rst,
  input wire dir, // 1 for up, 0 for down
  output reg [3:0] count
);
  always @(posedge clk or posedge rst) begin
    if (rst) count <= 0;
    else if (dir) count <= count + 1;
    else count <= count - 1;
  end
endmodule

This code counts up or down by 1 on each clock pulse depending on the direction signal.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The counting update happens once every clock cycle.
  • How many times: It repeats for each clock pulse, which depends on how long the system runs.
How Execution Grows With Input

Each clock cycle triggers one count update, so the number of operations grows directly with the number of clock cycles.

Input Size (n)Approx. Operations
1010 count updates
100100 count updates
10001000 count updates

Pattern observation: The operations grow linearly as the input size (number of clock cycles) increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the counter grows directly in proportion to how many times it counts.

Common Mistake

[X] Wrong: "The counter updates all bits at once, so it takes constant time regardless of count size."

[OK] Correct: While the hardware updates all bits simultaneously, the number of updates depends on the number of clock cycles, which grows with input time, not the bit width.

Interview Connect

Understanding how simple counters scale helps you reason about timing and performance in hardware design, a key skill for many projects.

Self-Check

"What if we changed the counter to count by 2 instead of 1 each cycle? How would the time complexity change?"