Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get millisecond timestamp #5

Closed
Vxider opened this issue Mar 2, 2018 · 2 comments
Closed

get millisecond timestamp #5

Vxider opened this issue Mar 2, 2018 · 2 comments

Comments

@Vxider
Copy link

Vxider commented Mar 2, 2018

Thank you for your Tutorial. This code will result ntp time in seconds. How can I get millisecond timestamp, I don't know how to combine txTm_s and txTm_f. And if NTP server's network latency is less then 1ms, the ntp time error in this code will less then 1ms ?

@lettier
Copy link
Owner

lettier commented Mar 3, 2018

Hello @Vxider. I am glad you enjoyed the tutorial.

So as you know the txTm_s value is the number of seconds since the NTP epoch (1900-01-01 00:00:00) and we subtract 70 years worth of seconds to get the number of seconds since the UNIX Epoch (1970-01-01 00:00:00).

The txTm_f value represents a fraction or proportion of a second. It is unit less in terms of the standard sub-second units of time. According to the RFC, one second == 2^32-1 == 4294967295 == 11111111111111111111111111111111 (32 bits) [0]. Depending on your needs, you could go with timeval which uses microseconds or timespec which uses nanoseconds [1].

Still, if you want to combine the two and convert the unit of measure to milliseconds you could do the following.

  // Seconds since UNIX epoch.
  uint32_t txTm = packet.txTm_s - NTP_TIMESTAMP_DELTA;
  // Convert seconds to milliseconds.
  double milliseconds = (double) txTm * 1000.0;
  // Add fractional part.
  milliseconds += ((double) packet.txTm_f / 4294967295) * 1000.0;
  printf("Milliseconds since UNIX epoch: %f\n", milliseconds);

You can check the result with this tool.

For dealing with latency, see issue #4.

According to the RFC, "With NTPv4, servers and clients are precise within a few tens of milliseconds with poll intervals up to 36 hours." [0]

👍

[0] https://tools.ietf.org/search/rfc5905
[1] https://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html

@Vxider
Copy link
Author

Vxider commented Mar 3, 2018

Thanks for your explanation, and it solved my problem. 👍

@Vxider Vxider closed this as completed Mar 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants