简体   繁体   English

如何使 nftw() 更快

[英]How to make nftw() faster

I am working on a directory listing project and I need to capture all the files on the computer and then store them in a queue, which will then be sent off for worker threads to do work on.我正在处理一个目录列表项目,我需要捕获计算机上的所有文件,然后将它们存储在队列中,然后将其发送给工作线程以进行处理。

Right now I am using this example code of nftw() :现在我正在使用nftw()这个示例代码

#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static int
display_info(const char *fpath, const struct stat *sb,
             int tflag, struct FTW *ftwbuf)
{
    printf("%-3s %2d %7jd   %-40s %d %s\n",
        (tflag == FTW_D) ?   "d"   : (tflag == FTW_DNR) ? "dnr" :
        (tflag == FTW_DP) ?  "dp"  : (tflag == FTW_F) ?   "f" :
        (tflag == FTW_NS) ?  "ns"  : (tflag == FTW_SL) ?  "sl" :
        (tflag == FTW_SLN) ? "sln" : "???",
        ftwbuf->level, (intmax_t) sb->st_size,
        fpath, ftwbuf->base, fpath + ftwbuf->base);
    return 0;           /* To tell nftw() to continue */
}

int
main(int argc, char *argv[])
{
    int flags = 0;

   if (argc > 2 && strchr(argv[2], 'd') != NULL)
        flags |= FTW_DEPTH;
    if (argc > 2 && strchr(argv[2], 'p') != NULL)
        flags |= FTW_PHYS;

   if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags)
            == -1) {
        perror("nftw");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}

I have noticed that it starts out very fast and then dies off pretty quick and each 1000 files looped through takes roughly 7 seconds.我注意到它开始非常快,然后很快就消失了,每循环 1000 个文件大约需要 7 秒。 I am looking for a way to increase the speed for this function.我正在寻找一种方法来提高此功能的速度。

In the page that you linked, there is this explanation for this behavior:在您链接的页面中,对此行为有以下解释:

To avoid using up all of the calling process's file descriptors, nopenfd specifies the maximum number of directories that ftw() will hold open simultaneously.为了避免用完所有调用进程的文件描述符, nopenfd指定了ftw()将同时打开的最大目录数。 When the search depth exceeds this, ftw() will become slower because directories have to be closed and reopened.当搜索深度超过此值时, ftw()将变慢,因为必须关闭并重新打开目录。 ftw() uses at most one file descriptor for each level in the directory tree. ftw()对目录树中的每一层至多使用一个文件描述符。

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

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