0
0
Verilogprogramming~5 mins

If-else in always blocks in Verilog - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If-else in always blocks
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run if-else statements inside always blocks changes as the input changes.

Specifically, we ask: does adding more conditions make the code slower?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

always @(posedge clk) begin
  if (cond1) begin
    out = in1;
  end else if (cond2) begin
    out = in2;
  end else begin
    out = in3;
  end
end

This code chooses one of three inputs based on conditions every clock cycle.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The if-else checks inside the always block.
  • How many times: Once per clock cycle, checking conditions in order.
How Execution Grows With Input

Each clock cycle, the code checks conditions one by one until one is true.

Input Size (number of conditions)Approx. Operations per cycle
11 check
3Up to 3 checks
10Up to 10 checks

Pattern observation: The number of checks grows linearly with the number of conditions.

Final Time Complexity

Time Complexity: O(n)

This means the time to decide grows in a straight line as you add more conditions.

Common Mistake

[X] Wrong: "If-else statements run all conditions every time no matter what."

[OK] Correct: The checks stop as soon as one condition is true, so not all conditions run every time.

Interview Connect

Understanding how if-else conditions affect execution helps you explain how hardware decisions happen step-by-step.

Self-Check

"What if we replaced if-else with multiple independent if statements? How would the time complexity change?"