Nios® II Software Developer Handbook

ID 683525
Date 8/28/2023
Public
Document Table of Contents

7.9.3. Timestamp Driver

Sometimes you want to measure time intervals with a degree of accuracy greater than that provided by HAL system clock ticks. The HAL provides high resolution timing functions using a timestamp driver. A timestamp driver provides a monotonically increasing counter that you can sample to obtain timing information. The HAL only supports one timestamp driver in the system.

You specify a hardware timer peripheral as the timestamp device by manipulating BSP settings. The Intel FPGA-provided timestamp driver uses the timer that you specify.

If a timestamp driver is present, the following functions are available:

  • alt_timestamp_start()
  • alt_timestamp()

Calling alt_timestamp_start() starts the counter running. Subsequent calls to alt_timestamp() return the current value of the timestamp counter. Calling alt_timestamp_start() again resets the counter to zero. The behavior of the timestamp driver is undefined when the counter reaches (232 - 1).

You can obtain the rate at which the timestamp counter increments by calling the function alt_timestamp_freq(). This rate is typically the hardware frequency of the Nios® II processor system—usually millions of cycles per second. The timestamp drivers are defined in the alt_timestamp.h header file.

For more information about the use of these functions, refer to the HAL API Reference section.

Example 6–9. Using the Timestamp to Measure Code Execution Time

#include <stdio.h>
#include "sys/alt_timestamp.h"
#include "alt_types.h"
int main (void)
{
alt_u32 time1;
alt_u32 time2;
alt_u32 time3;
if (alt_timestamp_start() < 0)
{
printf ("No timestamp device available\n");
}
else
{
time1 = alt_timestamp();
func1(); /* first function to monitor */
time2 = alt_timestamp();
func2(); /* second function to monitor */
time3 = alt_timestamp();
printf ("time in func1 = %u ticks\n",
(unsigned int) (time2 - time1));
printf ("time in func2 = %u ticks\n",
(unsigned int) (time3 - time2));
printf ("Number of ticks per second = %u\n",
(unsigned int)alt_timestamp_freq());
}
return 0;
}