简体   繁体   English

无限循环与boost :: asio :: deadline_timer C ++性能

[英]infinite loop vs boost::asio::deadline_timer C++ performance

I develop a server application that handles many connections from clients. 我开发了一个服务器应用程序,可以处理来自客户端的许多连接。 Server sends message to each clients periodically(ex: every 1 second), check for client's expiry times(each client must be disconnected from the server forcibly when connected time reaches a predetermined value) and some other timer tasks. 服务器定期向每个客户端发送消息(例如,每1秒发送一次),检查客户端的到期时间(当连接时间达到预定值时,必须强制每个客户端与服务器断开连接)以及一些其他计时器任务。 I consider 2 solutions: 我考虑2解决方案:

  1. use while(true){foreach clients{check time}} 使用while(true){foreach客户{check time}}
  2. for each client, delcare a deadline_timer and call async_wait for each task, so it will spawn a lot of deadline_timer instances 对于每个客户端,delcare都指定了一个duration_timer并为每个任务调用async_wait,因此它将产生大量的duration_timer实例

Which solution is better for performance? 哪种解决方案性能更好? In general, Should I use infinite loop or declaring many timer instances? 通常,我应该使用无限循环还是声明许多计时器实例? And one more, Can you explain how OS manages deadline_timer? 还有一件事,您能解释一下操作系统如何管理截止时间吗?

Q. Which solution is better for performance? 问:哪种解决方案性能更好?

Infinite loops are usually bad. 无限循环通常是不好的。 Exceptions to be found in CPU-saturating workers with thread affinity (but that doesn't appear to be applicable here). 在具有线程相似性的CPU饱和工作器中会发现异常(但似乎不适用于此处)。

Q. In general, Should I use infinite loop 问:一般来说,我应该使用无限循环吗

No 没有

Q. or declaring many timer instances? 或声明许多计时器实例?

Or just 要不就

std::vector<boost::shared_ptr<asio::deadline_timer> > m_timers;

or similar :) 或类似的:)

Q. And one more, Can you explain how OS manages deadlien_timer? 问:还有,您能解释一下操作系统如何管理deadlien_timer吗?

The timers are using platform specific kernel events, under the hood. 计时器在后台使用平台特定的内核事件。 Meaning, in practice, that if you have eg 10 tasks all blocked on different timers, the kernel will keep the process in sleep state (not running at all) until the first one expires. 实际上,这意味着,例如,如果您有10个任务在不同的计时器上全部阻塞,则内核将使进程保持睡眠状态(根本不运行),直到第一个任务到期为止。

Kernel-level synchronization primitives are in general the fastest way for non-CPU bound work loads, by far. 通常,到目前为止,内核级同步原语是不受CPU限制的工作负载的最快方法。

Do you require each client timeout at exactly(or almost) one second? 您是否要求每个客户端超时精确(或几乎)一秒?

I would do third way: 我会做第三种方式:

while (true) {
  if ( elapsed_one_second() ) {
    for each client {
      client->check_timeout();
    }
}

Or if you have event queue, you do one timer to trigger the checking of all clients. 或者,如果您有事件队列,则可以使用一个计时器触发对所有客户端的检查。

EDIT: If you have huge amount of timers, you may also consider implement a delta queue and use one-shot timer for the earliest event. 编辑:如果您有大量的计时器,您也可以考虑实现增量队列,并在最早的事件中使用一次性计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM