Most efficient way to randomize payload and length?

What is the most efficient way to randomize the length and payload? Is it to randomize the length and in the task post_randomize(), use a foreach loop on the payload array and use $random()?

In reply to VerifEx:

What is the most efficient way to randomize the length and payload? Is it to randomize the length and in the task post_randomize(), use a foreach loop on the payload array and use $random()?

Below is code from http://www.simantis.com/products.php


class payload;
	rand int unsigned data [];   // dynamic array 
	rand int unsigned length;  
	constraint c1_ct { length < 1024; length > 0;}
	constraint c2_ct {data.size() == length;}
endclass

module test; 
	payload p_c=new();
	int lgth; 
	int unsigned d; 
	initial 
		repeat (5) begin 	
		if (!randomize(p_c)) $display("error"); 
		lgth = p_c.length;
		d=p_c.data[0];
		$display("lgth = %d, d= %d", lgth, d);  
		end 
endmodule 

Ben Cohen ben@SystemVerilog.us

  • SVA Handbook 4th Edition, 2016 ISBN 978-1518681448
  • A Pragmatic Approach to VMM Adoption 2006 ISBN 0-9705394-9-5
  • Using PSL/SUGAR for Formal and Dynamic Verification 2nd Edition, 2004, ISBN 0-9705394-6-0
  • Real Chip Design and Verification Using Verilog and VHDL, 2002 isbn 0-9705394-2-8
  • Component Design by Example ", 2001 ISBN 0-9705394-0-1
  • VHDL Coding Styles and Methodologies, 2nd Edition, 1999 ISBN 0-7923-8474-1
  • VHDL Answers to Frequently Asked Questions, 2nd Edition ISBN 0-7923-8115

As Ben’s example shows, the payload elements are randomized as well as the size of the array. There is no need to use the post_randomize() function.

Here is the relevant LRM section 18.4:

— Arrays can be declared rand or randc, in which case all of their member elements are treated as rand or randc.
— Individual array elements can be constrained, in which case the index expression may include iterative constraint loop variables, constants, and state variables.
— Dynamic arrays, associative arrays and queues can be declared rand or randc. All of the elements in the array are randomized, overwriting any previous data.

In reply to cgales:

A slightly more efficient example:

class payload;
	rand int unsigned data [];   // dynamic array 
	constraint data_size { data.size() inside {[0:1024]}; } 
	constraint data_elem { foreach (data[ii]) data[ii] < ii; } // constraint on each element
endclass

BTW, never ever use $random in a SystemVerilog testbench; use $urandom instead. This gives you stability and command line control over seeding.

In reply to ben@SystemVerilog.us:

What I don’t understand is that how does the dynamic array allocate the size without using the new operator? How does randomizing data.size() allocate memory?

In reply to VerifEx:
Read section 18.4 Random variables in the 180-2012 LRM; especially the bullets that mention dynamic arrays.