echolin
Posts: 8
Joined: Mon Mar 23, 2020 8:07 am

How to measure time with nanosecond accuracy?

Mon Mar 23, 2020 8:31 am

Hi, everyone.
In my project, I want to measure the difference of delta-T between two event pairs. How can I get the register value which records the ticks? Because the resolution I need is very high, I think the clock frequency of the timer should be adequately high too. Thanks!

Heater
Posts: 14685
Joined: Tue Jul 17, 2012 3:02 pm

Re: How to measure time with nanosecond accuracy?

Mon Mar 23, 2020 10:57 am

Not something that can be done with a Pi.

You could get something like this: https://www.pctestinstruments.com/ to sample your signal at 500MHz giving a 2ns resolution.

By the way, do you mean "accuracy" or "resolution" these are not the same thing.

What is this signal you want to measure?
Memory in C++ is a leaky abstraction .

jahboater
Posts: 5172
Joined: Wed Feb 04, 2015 6:38 pm
Location: West Dorset

Re: How to measure time with nanosecond accuracy?

Mon Mar 23, 2020 11:55 am

This little function should (in theory) return the raw hardware counter without interference from NTP.
Its returned as a 64-bit unsigned integer.

Code: Select all

#include <time.h>

static uint64_t
counter( void )
{
  struct timespec now;
  clock_gettime( CLOCK_MONOTONIC_RAW, &now );
  return (uint64_t)now.tv_sec * UINT64_C(1000000000) + (uint64_t)now.tv_nsec;
}
However I doubt the real counter is anywhere near nano second resolution or accuracy - probably micro seconds.
"We are in the beginning of a mass extinction, and all you can talk
about is money and fairy tales of eternal economic growth."
- Greta Thunberg

LdB
Posts: 1476
Joined: Wed Dec 07, 2016 2:29 pm

Re: How to measure time with nanosecond accuracy?

Mon Mar 23, 2020 12:41 pm

There are quite a few "Time of Flight" hats and ultra high resolution timers available as a Pi Hat which may be more what you are looking for.

User avatar
mahjongg
Forum Moderator
Forum Moderator
Posts: 12653
Joined: Sun Mar 11, 2012 12:19 am
Location: South Holland, The Netherlands

Re: How to measure time with nanosecond accuracy?

Mon Mar 23, 2020 12:48 pm

Yes for nanosecond resolution you will almost certainly need external hardware, for example a time of flight (lightspeed) measuring device.

User avatar
HermannSW
Posts: 2006
Joined: Fri Jul 22, 2016 9:09 pm
Location: Eberbach, Germany
Contact: Website Twitter YouTube

Re: How to measure time with nanosecond accuracy?

Mon Mar 23, 2020 7:48 pm

I had 5$ 24Msps and 20$ 100Msps logic analyzers.
Some years ago I did pay 60$ for 400Msps logic analyzer on aliexpress, that can measure at resolution 2.5ns, and still does cost 60$ today:
https://www.aliexpress.com/af/400MHz-lo ... t=1&page=1
⇨https://stamm-wilbrandt.de/en/Raspberry_camera.html

https://github.com/Hermann-SW/Raspberry_v1_camera_global_external_shutter
https://stamm-wilbrandt.de/github_repo_i420toh264
https://github.com/Hermann-SW/fork-raspiraw
https://twitter.com/HermannSW

User avatar
mikronauts
Posts: 2749
Joined: Sat Jan 05, 2013 7:28 pm
Contact: Website

Re: How to measure time with nanosecond accuracy?

Mon Mar 23, 2020 8:10 pm

1ns requires counters that can count at 1GHz

Specialized, expensive.

As others have said time of flight equipment may work, but likely not at a price you would like.
echolin wrote:
Mon Mar 23, 2020 8:31 am
Hi, everyone.
In my project, I want to measure the difference of delta-T between two event pairs. How can I get the register value which records the ticks? Because the resolution I need is very high, I think the clock frequency of the timer should be adequately high too. Thanks!
http://Mikronauts.com - home of EZasPi, RoboPi, Pi Rtc Dio and Pi Jumper @Mikronauts on Twitter
Advanced Robotics, I/O expansion and prototyping boards for the Raspberry Pi

echolin
Posts: 8
Joined: Mon Mar 23, 2020 8:07 am

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 3:37 am

Thank you for replying.
I want to measure the time when the signal flies in the air using raspberry and LoRa modules.
LoRa module A is located 1km away from Lora module B.
They are supposed to run the "ping-pong" program 1k times.
I plan to record the elapsed time and subtract the time like MCU processing time and LoRa modem processing time by calibration.
Can I use the distance and time to calculate the speed of the signal (C)?
I mean "accuracy".
Heater wrote:
Mon Mar 23, 2020 10:57 am
Not something that can be done with a Pi.

You could get something like this: https://www.pctestinstruments.com/ to sample your signal at 500MHz giving a 2ns resolution.

By the way, do you mean "accuracy" or "resolution" these are not the same thing.

What is this signal you want to measure?

echolin
Posts: 8
Joined: Mon Mar 23, 2020 8:07 am

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 3:41 am

Thank you for replying.
It seems the price is indeed so high that it is not consistent with my original intention.


mikronauts wrote:
Mon Mar 23, 2020 8:10 pm
1ns requires counters that can count at 1GHz

Specialized, expensive.

As others have said time of flight equipment may work, but likely not at a price you would like.
echolin wrote:
Mon Mar 23, 2020 8:31 am
Hi, everyone.
In my project, I want to measure the difference of delta-T between two event pairs. How can I get the register value which records the ticks? Because the resolution I need is very high, I think the clock frequency of the timer should be adequately high too. Thanks!

echolin
Posts: 8
Joined: Mon Mar 23, 2020 8:07 am

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 4:28 am

Thanks for replying.
This logic analyzer is competent enough and I can afford it.

HermannSW wrote:
Mon Mar 23, 2020 7:48 pm
I had 5$ 24Msps and 20$ 100Msps logic analyzers.
Some years ago I did pay 60$ for 400Msps logic analyzer on aliexpress, that can measure at resolution 2.5ns, and still does cost 60$ today:
https://www.aliexpress.com/af/400MHz-lo ... t=1&page=1

echolin
Posts: 8
Joined: Mon Mar 23, 2020 8:07 am

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 5:46 am

Thank you for replying.
I print out the result every second and calculate the time unit which is about 0.99985ns if there is no fault.

while(1){
sleep(1);
printf("%"PRIu64"\r\n", counter() );
}
It is just what I want, thanks again.



jahboater wrote:
Mon Mar 23, 2020 11:55 am
This little function should (in theory) return the raw hardware counter without interference from NTP.
Its returned as a 64-bit unsigned integer.

Code: Select all

#include <time.h>

static uint64_t
counter( void )
{
  struct timespec now;
  clock_gettime( CLOCK_MONOTONIC_RAW, &now );
  return (uint64_t)now.tv_sec * UINT64_C(1000000000) + (uint64_t)now.tv_nsec;
}
However I doubt the real counter is anywhere near nano second resolution or accuracy - probably micro seconds.

echolin
Posts: 8
Joined: Mon Mar 23, 2020 8:07 am

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 5:53 am

Thanks, I will have a try.
LdB wrote:
Mon Mar 23, 2020 12:41 pm
There are quite a few "Time of Flight" hats and ultra high resolution timers available as a Pi Hat which may be more what you are looking for.

echolin
Posts: 8
Joined: Mon Mar 23, 2020 8:07 am

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 5:59 am

Thanks! I didn't think of that before.
mahjongg wrote:
Mon Mar 23, 2020 12:48 pm
Yes for nanosecond resolution you will almost certainly need external hardware, for example a time of flight (lightspeed) measuring device.

Heater
Posts: 14685
Joined: Tue Jul 17, 2012 3:02 pm

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 8:40 am

Better to read the hardware system timer register directly. Here is an example code that does that:

Code: Select all

//
// Access the Raspberry Pi System Timer registers directly. 
//
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdint.h>

// #define PERIPHERAL_BASE 0x20000000   // For Pi 1 and 2
#define PERIPHERAL_BASE 0x3F000000      // For Pi 3
#define SYSTEM_TIMER_OFFSET 0x3000
#define ST_BASE (PERIPHERAL_BASE + SYSTEM_TIMER_OFFSET) 

// Sytem Timer Registers layout
typedef struct {
    uint32_t control_and_status;
    uint32_t counter_low;
    uint32_t counter_high;
    uint32_t compare_0;
    uint32_t compare_1;
    uint32_t compare_2;
    uint32_t compare_3;
} system_timer_t;

// Get access to the System Timer registers in user memory space.
system_timer_t * get_system_timer() {
    void *system_timer;
    int  fd;

    if ((fd = open("/dev/mem", O_RDWR | O_SYNC) ) < 0) {
        printf("can't open /dev/mem \n");
        exit(-1);
    }

    system_timer = mmap(
        NULL,
        4096,
        PROT_READ | PROT_WRITE,
        MAP_SHARED,
        fd,
        ST_BASE
    );

    close(fd);

    if (system_timer == MAP_FAILED) {
        printf("mmap error %d\n", (int)system_timer);  // errno also set!
        exit(-1);
    }
    return (system_timer_t*)system_timer;
}

int main(int argc, char **argv) {
    volatile system_timer_t* system_timer = get_system_timer();
    int32_t t0, t1;

    while (1) {
        t0 = system_timer->counter_low;
        sleep(1);
        t1 = system_timer->counter_low;
        printf ("Elaspsed = %d\n", t1 - t0);
        printf ("Conter high = %d\n", system_timer->counter_high);
        t0 = t1;
    }
    return 0;
}
Also better to read any events on GPIO pins directly from hardware registers. The above code maps in all registers so you can do that as well easily. See example codes for reading GPIO registers directly here: https://elinux.org/RPi_GPIO_Code_Sample ... ter_access

Also better to ensure that whatever code is doing that time measurement is not disturbed by Linux process rescheduling. That can be achieved by isolating a CPU from the kernel with the "isolcpus" option in the kernel boot command line, then running your code on the isolated CPU using the "taskset" commannd. I have instructions as to how to do that here: viewtopic.php?t=200793.

I still don't see this working out, what with all the delays in reading/writing whatever Lora device you have. Timer resolution , software jitter, etc.

Perhaps, possibly, maybe you will get a meaningful result as follows:

1) Have the remote LoRa station 1Km away.
2) Do your ping-pong timing hundreds or thousands of times and record the trip time.
3) Ignore the outliers, extra long times, and take the average time of the rest.
4) Move your remote station to 2Km away.
5) Repeat steps 2) and 3)

At the end of that you have an average trip time at 1Km and another at 2km, the difference between those is now only due to the extra Km of distance. This neatly cancels out all the hardware/software timing overheads exactly. Assuming you manage to get a noticeable difference in those average times.
Memory in C++ is a leaky abstraction .

jahboater
Posts: 5172
Joined: Wed Feb 04, 2015 6:38 pm
Location: West Dorset

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 10:32 am

The only problem with that is the requirement for root privilege.
The system call (which I suspect returns the same counter) does not - and the code is much simpler.
"We are in the beginning of a mass extinction, and all you can talk
about is money and fairy tales of eternal economic growth."
- Greta Thunberg

Heater
Posts: 14685
Joined: Tue Jul 17, 2012 3:02 pm

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 12:30 pm

jahboater wrote:
Tue Mar 24, 2020 10:32 am
The only problem with that is the requirement for root privilege.
The system call (which I suspect returns the same counter) does not - and the code is much simpler.
That is true.

However for the purposes of solving my problem on my machine with my software the requirement for root privileges is not a problem.

Likely that system call does get one the same counter, but it requires running through a ton of library code and the kernel and possible involves rescheduling etc.

The point of my suggestion was to get rid of all that and get as close to the "metal" as possible.
Memory in C++ is a leaky abstraction .

jahboater
Posts: 5172
Joined: Wed Feb 04, 2015 6:38 pm
Location: West Dorset

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 1:56 pm

Heater wrote:
Tue Mar 24, 2020 12:30 pm
Likely that system call does get one the same counter, but it requires running through a ton of library code and the kernel and possible involves rescheduling etc.

The point of my suggestion was to get rid of all that and get as close to the "metal" as possible.
Yes agreed.

Its probably going through the kernel that has the biggest overhead.
The ABI is the same for library functions as it is for system calls, so in many cases the library function needs little more than "svc 0" or "syscall" because the arguments are already in the correct registers.
"We are in the beginning of a mass extinction, and all you can talk
about is money and fairy tales of eternal economic growth."
- Greta Thunberg

LdB
Posts: 1476
Joined: Wed Dec 07, 2016 2:29 pm

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 3:17 pm

echolin wrote:
Tue Mar 24, 2020 3:37 am
I want to measure the time when the signal flies in the air using raspberry and LoRa modules.
LoRa module A is located 1km away from Lora module B.
They are supposed to run the "ping-pong" program 1k times.
You are going to struggle with this simple device setup you will need them absolute line of site and lifted from the ground so the don't reflect.

The moment you get much reflection you are dead in the water
https://en.wikipedia.org/wiki/Multipath_propagation
The ability to tell the difference between two different path lengths is the simple formula

Speed of Light / bandwidth
300000000 / 125 kHz = 2400 m

The lora signal is very narrow band if the band was 1Mhz wide the difference drops to 300m, 10Mhz it's 30m

To do it with any accuracy you need a whole other layer only available on proper gateways which has Time Difference of Arrival setup.

PiGraham
Posts: 3778
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How to measure time with nanosecond accuracy?

Tue Mar 24, 2020 4:29 pm

This talk may be relevant although it doesn't answer the OP question.

Richard Lansdowne - LoRa Geolocation

https://www.youtube.com/watch?v=WEqLESKW6N8

echolin
Posts: 8
Joined: Mon Mar 23, 2020 8:07 am

Re: How to measure time with nanosecond accuracy?

Wed Mar 25, 2020 4:50 am

Thanks!
It is very enlightening to me.
PiGraham wrote:
Tue Mar 24, 2020 4:29 pm
This talk may be relevant although it doesn't answer the OP question.

Richard Lansdowne - LoRa Geolocation

https://www.youtube.com/watch?v=WEqLESKW6N8

Return to “C/C++”