SystemVerilog Reference

Clocking Blocks

A clocking block fixes when a testbench samples and drives signals, relative to a clock edge.

Syntax

clocking cb @(posedge clk);
  default input #1step output #2;
  input  ready;
  output valid, data;
endclocking

Rules

  • Inputs are sampled just before the edge (#1step), so the testbench sees the pre-edge value.
  • Outputs are driven after the edge by the output skew.
  • Drive through the block with <=: cb.valid <= 1;.
  • @(cb); waits for the clocking event.
  • ##2; waits two clocking events when a default clocking is set.
  • This removes races between the testbench and the design.

Example

module tb;
  logic clk = 0;
  logic [3:0] count = 0;
  always #5 clk = ~clk;
  always @(posedge clk) count <= count + 1;

  clocking cb @(posedge clk);
    input count;
  endclocking

  initial begin
    repeat (3) begin
      @(cb);
      $display("t=%0t sampled=%0d", $time, cb.count);
    end
    $finish;
  end
endmodule
Output on Verilator 5.052
t=5 sampled=0
t=15 sampled=1
t=25 sampled=2

Run It in the Playground

Common Mistake

Reading the raw signal after waiting on the clocking block

@(cb);
if (ready) ...      // raw signal: may be the old or the new value
if (cb.ready) ...   // sampled value: always the pre-edge value

The raw signal can change on the same edge, so what you read depends on process order.

Fix: Read inputs through the clocking block: cb.ready.

Learn It Properly

These lessons teach it step by step, with practice problems.

Standard

IEEE 1800-2023, 14.3.