If-else in always blocks in Verilog - Time & Space 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?
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 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.
Each clock cycle, the code checks conditions one by one until one is true.
| Input Size (number of conditions) | Approx. Operations per cycle |
|---|---|
| 1 | 1 check |
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
Pattern observation: The number of checks grows linearly with the number of conditions.
Time Complexity: O(n)
This means the time to decide grows in a straight line as you add more conditions.
[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.
Understanding how if-else conditions affect execution helps you explain how hardware decisions happen step-by-step.
"What if we replaced if-else with multiple independent if statements? How would the time complexity change?"