Skip navigation.
Home

SystemVerilog Constrained Random Variables

SystemVerilog introduced the built in support for constrained random variables. A variable can be made into a random variable by putting the "rand" keyword before the variable. Constraints can be applied to the variable by creating a constraint{} block and listing the constraints for the variable inside the block. This snippet demonstrates how to create a basic constrained random variable that represents a random pulse.

class RandPulse;
  rand int pulse_width;   // variables that can be randomized.
  rand int before_time;
  rand int after_time;
 
  // the constraints on the random variables.
  constraint c { pulse_width <= 100;  
    pulse_width >= 1;
    before_time >= 10;
    before_time <= 100;
    after_time >= 5;
    after_time <= 200;
  }
 
  // display the values of the random variables.
  function display_class();
    $display("before_time = %d",before_time);
    $display("pulse_width = %d",pulse_width);
    $display("after_time = %d",after_time);
  endfunction
endclass
 
 
module rand_pulse_gen;
bit clk;
logic pulse;
 
initial begin 
  forever #10 clk = ~clk;
end
 
initial begin
  RandPulse r1 = new();
  // generate 20 random pulses.
  repeat (20) begin
    assert(r1.randomize());    // randomize the variables.
    r1.display_class();        // display them.
    pulse = 0;                 // generate the pulse.
    repeat (r1.before_time) @(posedge clk);
    pulse = 1;
    repeat (r1.pulse_width) @(posedge clk);
    pulse = 0;
    repeat (r1.after_time) @(posedge clk);
  end
  $stop;
end
 
endmodule

AttachmentSize
constrained_random.sv1.12 KB