A given set of statements can be executed N number of times with a repeat
construct.
Syntax
repeat (<number>)
// Single Statement
repeat (<number>) begin
// Multiple Statements
end
Example #1
module tb;
initial begin
repeat (5) begin
$display ("Repeat this statement");
end
end
endmodule
Simulation Log
ncsim> run Repeat this statement Repeat this statement Repeat this statement Repeat this statement Repeat this statement ncsim: *W,RNQUIE: Simulation is complete.
A repeat
loop can also be implemented using a for
loop but is more verbose. If the variable i is not required to be referenced inside the loop, a repeat
loop would be more suitable.
for (int i = 0; i < number; i++) begin
// Code
end
In the code shown below, we have a repeat
loop to wait for a given number of clock cycles.
module tb;
bit clk;
always #10 clk = ~clk;
initial begin
bit [2:0] num = $random;
$display ("[%0t] Repeat loop is going to start with num = %0d", $time, num);
repeat (num) @(posedge clk);
$display ("[%0t] Repeat loop has finished", $time);
$finish;
end
endmodule
In this example, the clock period is 20 ns, and the first posedge of clock happens at 10 ns. Next 3 posedge of clock happens at 30ns, 50ns and 70ns after which the initial block ends. So, this repeat
loop successfully waits until 4 posedge of clocks are over.
Simulation Log
ncsim> run [0] Repeat loop is going to start with num = 4 [70] Repeat loop has finished Simulation complete via $finish(1) at time 70 NS + 0