1

I have found this question related to chrono time_since_epoch() function.With the answers given in that thread we can achieve timestamping in same machine in multiple platforms. I have two machines which are showing two different time_since_epoch() in microseconds.I need to timestamp a packet sent from one machine to the other machine to calculate the latecy of that packet.

Currently I have used

    uint64_t usCurrentTime = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count(); 

function to get the current time since epoch in microseconds.But the latency is underflowing since I am saving it in uint64_t.This is because both the machines are not in time sync. How can I achieve my need using chrono library functions

Kethiri Sundar
  • 480
  • 2
  • 12

2 Answers2

3

There is no timestamp you have ready access to that will ensure that the receiver's timestamp is larger than the sender's timestamp. The only clock that produces values that can be compared meaningfully between machines is system_clock, and that is 'system time', i.e. what your PC displays as the current time; they need not be in sync. You're going to have to be cleverer.

C++20 will offer a tai_clock, utc_clock and gps_clock, one of which is likely to suit your needs (but bad synchronisation could result in a negative timestamp difference still!).

A possible approach: machine 1 sends machine 2 a packet with a std::chrono::high_resolution_clock timestamp in it. Machine 2 sends it back. Machine 1 receives the returned packet and compares the received timestamp to std::chrono::high_resolution_clock::now() then divides by 2.

James Picone
  • 1,509
  • 9
  • 18
  • I really liked the first two paragraphs in this answer. Using `high_resolution_clock` for this purpose is like two people synchronizing two different stopwatches, while keeping secret when each stopwatch was started. – Howard Hinnant Oct 31 '18 at 13:44
  • 1
    @HowardHinnant The algorithm I'm trying to describe is person 1 sending a stopwatch to person 2, person 2 sending the stopwatch back, and then person 1 looking at what the stopwatch says. Machine 2 is sending back the exact packet it received, with the Machine 1 timestamp in it; Machine 1 can meaningfully compare that timestamp with new `high_resolution_clock` timestamps. I think? Am I missing something? – James Picone Nov 01 '18 at 14:10
  • Oh, I see. You're getting the round trip latency by comparing time stamps on just one side. I misunderstood. Yes, that seems reasonable. – Howard Hinnant Nov 01 '18 at 15:08
0

maybe a third machine in the same LAN can be used as the timestamp source, the other two machines receive it's timestamp in messages and calculate timestamp difference.

Brent81
  • 1,152
  • 1
  • 13
  • 19