Epoch in VHDL

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since a specific reference point. In VHDL, we don’t have a built-in concept of Unix epoch, but we can simulate it using a custom function and the now attribute.

library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;

entity epoch_example is
end epoch_example;

architecture behavior of epoch_example is
    constant REFERENCE_TIME : time := 0 ns; -- Our "epoch"
    
    function get_elapsed_time(unit : time) return integer is
    begin
        return (now - REFERENCE_TIME) / unit;
    end function;
    
begin
    process
        variable elapsed_seconds : integer;
        variable elapsed_milliseconds : integer;
        variable elapsed_nanoseconds : integer;
    begin
        -- Simulate passage of time
        wait for 1234567890 ns;
        
        -- Get elapsed time in different units
        elapsed_seconds := get_elapsed_time(1 sec);
        elapsed_milliseconds := get_elapsed_time(1 ms);
        elapsed_nanoseconds := get_elapsed_time(1 ns);
        
        -- Print results
        report "Elapsed seconds: " & integer'image(elapsed_seconds);
        report "Elapsed milliseconds: " & integer'image(elapsed_milliseconds);
        report "Elapsed nanoseconds: " & integer'image(elapsed_nanoseconds);
        
        wait;
    end process;
end behavior;

In this VHDL example, we define a constant REFERENCE_TIME as our “epoch” starting point. We then create a custom function get_elapsed_time that calculates the time elapsed since this reference point in the specified unit.

In the main process, we:

  1. Simulate the passage of time using a wait statement.
  2. Calculate the elapsed time in seconds, milliseconds, and nanoseconds using our custom function.
  3. Print the results using report statements.

To run this VHDL code, you would typically use a VHDL simulator. The exact commands may vary depending on your simulation environment, but it might look something like this:

$ ghdl -a epoch_example.vhd
$ ghdl -e epoch_example
$ ghdl -r epoch_example
Elapsed seconds: 1
Elapsed milliseconds: 1234
Elapsed nanoseconds: 1234567890

Note that VHDL is primarily used for hardware description and simulation, so the concept of “running” a program is different from software languages. The simulation will run the process and report the results based on the simulated time progression.

Next, we’ll look at other time-related tasks in VHDL, such as creating and using custom time types and formats.