为什么 epoll 比 select 快? [英] Why is epoll faster than select?

查看:46
本文介绍了为什么 epoll 比 select 快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多比较说 select 必须遍历 fd 列表,这很慢.但是为什么 epoll 不必这样做呢?

I have seen a lot of comparisons which says select have to walk through the fd list, and this is slow. But why doesn't epoll have to do this?

推荐答案

有很多关于这个的错误信息,但真正的原因是:

There's a lot of misinformation about this, but the real reason is this:

一个典型的服务器可能要处理 200 个连接.它将为需要写入或读取数据的每个连接提供服务,然后需要等到有更多工作要做.在等待期间,如果在这 200 个连接中的任何一个上接收到数据,则需要将其中断.

A typical server might be dealing with, say, 200 connections. It will service every connection that needs to have data written or read and then it will need to wait until there's more work to do. While it's waiting, it needs to be interrupted if data is received on any of those 200 connections.

使用select,内核必须将进程添加到200 个等待列表中,每个连接一个.为此,它需要一个thunk"将进程附加到等待列表.当进程最终唤醒时,需要从所有 200 个等待列表中删除它,并且需要释放所有这些 thunk.

With select, the kernel has to add the process to 200 wait lists, one for each connection. To do this, it needs a "thunk" to attach the process to the wait list. When the process finally does wake up, it needs to be removed from all 200 wait lists and all those thunks need to be freed.

相比之下,对于epollepoll 套接字本身有一个等待列表.该过程只需要使用一个 thunk 就可以放在那个等待列表中.当进程唤醒时,它只需要从一个wait list中移除,并且只需要释放一个thunk.

By contrast, with epoll, the epoll socket itself has a wait list. The process needs to be put on only that one wait list using only one thunk. When the process wakes up, it needs to be removed from only one wait list and only one thunk needs to be freed.

需要明确的是,使用 epollepoll 套接字本身必须附加到这 200 个连接中的每一个.但是,对于每个连接,当它首先被接受时,就完成一次.对于每个连接,当它被移除时,它会被拆除一次.相比之下,每次调用 select 都必须将进程添加到每个被监控套接字的等待队列中.

To be clear, with epoll, the epoll socket itself has to be attached to each of those 200 connections. But this is done once, for each connection, when it is accepted in the first place. And this is torn down once, for each connection, when it is removed. By contrast, each call to select that blocks must add the process to every wait queue for every socket being monitored.

具有讽刺意味的是,使用 select 时,最大的成本来自检查没有活动的套接字是否有任何活动.使用 epoll,无需检查没有活动的套接字,因为如果它们确实有活动,他们会在活动发生时通知 epoll 套接字.从某种意义上说,每次调用 select 时,select 都会轮询每个 socket 以查看是否有任何活动,而 epoll 会操纵它以便 socket 活动本身通知进程.

Ironically, with select, the largest cost comes from checking if sockets that have had no activity have had any activity. With epoll, there is no need to check sockets that have had no activity because if they did have activity, they would have informed the epoll socket when that activity happened. In a sense, select polls each socket each time you call select to see if there's any activity while epoll rigs it so that the socket activity itself notifies the process.

这篇关于为什么 epoll 比 select 快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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