FIFO buffer design concept in Verilog - Time & Space Complexity
When designing a FIFO buffer in Verilog, it's important to understand how the time to process data grows as the buffer size changes.
We want to know how the number of operations changes when we add more data to the buffer.
Analyze the time complexity of the following FIFO buffer code snippet.
module fifo #(parameter DEPTH = 16, WIDTH = 8) (
input clk, reset,
input wr_en, rd_en,
input [WIDTH-1:0] data_in,
output reg [WIDTH-1:0] data_out,
output reg full, empty
);
reg [WIDTH-1:0] mem [0:DEPTH-1];
reg [$clog2(DEPTH)-1:0] wr_ptr = 0, rd_ptr = 0;
always @(posedge clk) begin
if(reset) begin
wr_ptr <= 0; rd_ptr <= 0;
full <= 0; empty <= 1;
end else begin
if(wr_en && !full) begin
mem[wr_ptr] <= data_in;
wr_ptr <= wr_ptr + 1;
end
if(rd_en && !empty) begin
data_out <= mem[rd_ptr];
rd_ptr <= rd_ptr + 1;
end
full <= (wr_ptr == DEPTH-1);
empty <= (wr_ptr == rd_ptr);
end
end
endmodule
This code implements a FIFO buffer that stores data in memory and uses pointers to track where to write and read.
Look for operations that happen repeatedly as data moves through the FIFO.
- Primary operation: Writing to and reading from memory at pointer positions.
- How many times: Each write or read happens once per clock cycle when enabled.
The FIFO processes one data item per clock cycle when enabled, regardless of buffer size.
| Input Size (DEPTH) | Approx. Operations per Data Item |
|---|---|
| 10 | 1 write + 1 read per item |
| 100 | 1 write + 1 read per item |
| 1000 | 1 write + 1 read per item |
Pattern observation: The number of operations per data item stays the same no matter how big the buffer is.
Time Complexity: O(1)
This means each data item is handled in a fixed amount of time, no matter how large the FIFO buffer is.
[X] Wrong: "The time to write or read data grows as the buffer size increases because the pointers have to move through the whole buffer."
[OK] Correct: The pointers just move by one position each cycle, and the memory access is direct, so the time per operation stays constant.
Understanding FIFO time complexity shows you can reason about hardware efficiency and how designs scale, a key skill in hardware and embedded system roles.
What if we changed the FIFO to use a software loop to shift all data on each write? How would the time complexity change?