$time vs $realtime

Hi,

Please look below code snippets and their outputs

Code 1 with $realtime

`timescale 10ns/1ns

module p_array;

  logic clk;
  logic a;
 
  initial
    clk = 0;

  always begin
    #50 clk = ~clk;
  end

  initial begin
    #1.55 a = 0;
    #1.55 a = 1;
    #50 $stop;
  end

  initial
    $monitor(" Time = %0t, clk = %0b, a = %0b ", $realtime, clk, a);

  initial begin
    $dumpfile("dump.vcd");
    $dumpvars(0, p_array);
  end
endmodule: p_array

output

run -all
#  Time = 0, clk = 0, a = x 
#  Time = 16, clk = 0, a = 0 
#  Time = 32, clk = 0, a = 1 
#  Time = 500, clk = 1, a = 1

Code 2 with $time

// or browse Examples
`timescale 10ns/1ns

module p_array;

  logic clk;
  logic a;
 
  initial
    clk = 0;

  always begin
    #50 clk = ~clk;
  end

  initial begin
    #1.55 a = 0;
    #1.55 a = 1;
    #50 $stop;
  end

  initial
    $monitor(" Time = %0t, clk = %0b, a = %0b ", $time, clk, a);

  initial begin
    $dumpfile("dump.vcd");
    $dumpvars(0, p_array);
  end
endmodule: p_array

output

run -all
#  Time = 0, clk = 0, a = x 
#  Time = 20, clk = 0, a = 0 
#  Time = 30, clk = 0, a = 1 
#  Time = 500, clk = 1, a = 1

Why in the second scenario the time is 20 instead of 16?

Thanks,

Mukul

In reply to mukul1996:

Since your time scale is 10ns, $realtime returns 1.6 and $time has to return an integer, so that gets rounded up to 2. Your timescale is 1ns, so the %t format will scale the value to represent nanoseconds, it multiplies the returned value by 10. Try changing %t to %g to see what is going on.

In reply to dave_59:

Hi Dave, Thanks for the explanation, but I got one more doubt. If I go by what you just said:

In case of $realtime, in simulation log, look at the Time = 32, don’t you think it should be Time = 31.

Method 1 : Adding time first, and then convert
#1.55 a= 0;
#1.55 a = 1; // 1.55 + 1.55 = 3.1, Now 3.1 * 10 should be 31.

Method 2 : If I first convert them, and then add:
#1.55 a = 0; // 1.6 → 16
#1.55 a = 1; // 1.6 → 16
Now, total time is 32. Which is correct in $realtime case and as shown in Simulation log.

But, now let me apply the method 1 in case of $time
#1.55 a = 0;
#1.55 a = 1; // 1.55 + 1.55 = 3.1 → 3.0 → 30 which is shown correct in simulation

Now, let’s take method 2 in case of $time
#1.55 a = 0; // 1.6 → 20
#1.55 a = 1; // 1.6 → 20
Now, total time is 40.

You see, for $realtime method 2 is correct in simulation log, whereas for $time method 1 is showing correct simulation. But I don’t think simulator will follow different algorithm for these two cases.

Please put some light on the above doubt.

Thanks,

Mukul

In reply to mukul1996:

Your use of $time or $realtime only affects the $display, it has no effect on simulation execution. #1.55 gets converted to the integer 16 time units. Of course if you were to use the result $time or $realtime in an expression and put it back into simulation, then you would have an issue.