自午夜以来,纳秒级延迟最短 [英] Get nanoseconds since midnight with the lowest latency

查看:103
本文介绍了自午夜以来,纳秒级延迟最短的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得自午夜以来当前的纳秒数,并具有最低的延迟.

I'd like to get the current number of nanoseconds since midnight, with the lowest latency.

我的平台是带有Clang的Linux/Centos 7.我不在意可移植性.

My platform is Linux/Centos 7 with Clang. I do not care about portability.

我找到了 <chrono>结构, 但它们除以秒/毫秒等即可得出结果.

I found this <chrono> struct, but they are dividing by seconds/milliseconds etc to get the result.

我还发现可以修改纳秒级的时间:

I also found this which could be modified for nanoseconds:

struct timeval tv;
int msec = -1;
if (gettimeofday(&tv, NULL) == 0)
{
    msec = ((tv.tv_sec % 86400) * 1000 + tv.tv_usec / 1000);
}

https://stackoverflow.com/a/10499119/997112

但是他们又使用了除法. 有什么更快的方法,可以避免模数和除数?

but again they are using a division. Is there anything quicker, avoiding modulus and divisions?

我认为最快的方法是:

  • 现在获取时间
  • 将小时,分钟秒数乘以必要的纳秒数,然后将当前的毫微秒数加到总数中

?

推荐答案

没有任何硬件可以提供纳秒级计数器.因此必须使用提供其他功能(例如"CPU周期")的硬件,并由某个地方的软件进行缩放.

There isn't any hardware that provides a nanoseconds counter; therefore hardware that provides something else (e.g. "CPU cycles") must be used and scaled by software somewhere.

Linux上的clock_gettime()函数将为您扩展到十亿分之一秒.更重要的是(取决于安全性与性能的折衷),这可以纯粹在用户空间中完成,从而避免调用内核API的开销(这可能比同等划分的开销至少贵10倍).

The clock_gettime() function on Linux will scale to nanoseconds for you. More importantly (depending on security vs. performance compromises) this may be done purely in user-space, avoiding the overhead of calling the kernel API (which is likely to be at least 10 times more expensive than a measly division).

但是;在这些规模上,您需要非常具体地了解您的实际需求.例如;在leap秒中会发生什么?两台计算机可能仅因一台计算机配置为涂抹leap秒而另一台计算机没有配置而不同意.

However; at these scales you need to be extremely specific about what you actually want. For example; what is expected during leap seconds? 2 computers can disagree simply because one is configured to smear leap seconds and the other isn't.

再举一个例子;如果您想计算延迟(例如"latency = current_time_at_receiver - time_packet_says_it_was_sent"),则可能有2台计算机不同步(例如,发送方的时钟比接收方的时钟晚几秒钟,因此延迟最终为负数);为了解决这个问题,您可能需要一个训练阶段(有点像NTP协议),在该阶段您尝试估算两台计算机的时间来源之间的初始时差,然后进行监视/跟踪(以尝试补偿任何长时间词条漂移).

For another example; if you want to calculate latency (e.g. like "latency = current_time_at_receiver - time_packet_says_it_was_sent") then 2 computers can be out of sync (e.g. the sender's clock being a few seconds behind the receiver's, so latency ends up being negative); and to deal with that you'll probably need a training phase (a bit like the NTP protocol) where you try to estimate the initial difference between the 2 computers' time sources, followed by monitoring/tracking (to try to compensate for any long term drift).

这篇关于自午夜以来,纳秒级延迟最短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆