维基百科指出,与旧的系统调用一次操作O(n)相比,epoll的操作复杂度为O(1) [2]。
http://en.wikipedia.org/wiki/Epoll
然而,在Linux-2.6.38的fs/eventpoll.c源代码中,它似乎使用了红黑树进行搜索实现,其时间复杂度为O(logN)。
/*
* Search the file inside the eventpoll tree. The RB tree operations
* are protected by the "mtx" mutex, and ep_find() must be called with
* "mtx" held.
*/
static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
{
实际上,我没有看到任何一个 man 页会说 epoll() 的复杂度是 O(1)。为什么它被称为 O(1)?
epoll
的运行时间是O(log(n)),就准备好的描述符而言,它是O(n),而就监视 描述符而言,它是O(1)——这也是epoll
的全部意义所在。添加/删除描述符是一件很少发生的事情,等待准备好则很频繁,您通常会将许多个描述符放入集合中,而这些描述符实际上都没有准备好。就此而言,虽然epoll
实际上并不 是真正的O(1),但是它在最重要的地方确实是如此。常见情况很快,不常见情况则不是。 - Damon