文件搜索程序

问题描述 投票:0回答:1

我正在编写一个程序来搜索计算机上的文件,并且遇到搜索需要很长时间才能完成的问题,在我看来,如何才能加快代码速度?

我使用SSD,我不知道确切的文件数量,但465 GB中,已占用279 GB

Visual Studio 具有最大优化(速度优先)(/O2)

void searchFiles(const std::string& searchQuery, const std::string& rootDir, std::vector<std::string>& results) {
    std::queue<fs::path> dirs;
    dirs.push(rootDir);

    while (!dirs.empty()) {
        fs::path currentDir = dirs.front();
        dirs.pop();

        try {
            for (const auto& entry : fs::directory_iterator(currentDir)) {
                if (fs::is_directory(entry)) {
                    dirs.push(entry.path());
                }
                else {
                    if (entry.path().filename().string().find(searchQuery) != std::string::npos) {
                        results.push_back(entry.path().string());
                    }
                }
            }
        }
        catch (const std::exception& e) { }
    }
}

这是调用该函数的代码

void ScannerFile::ScanningFile()
{

    for (size_t i = 0; i < defaultPath.size(); i++)
    {
        searchFiles(defaultPath[i], "C:\\", ModuleManager::resultFile);
    }
}

我试图以某种方式重写它,但没有意义,速度仍然没有改变

例如搜索一个视频文件94秒

C:\\Users\\mgrr\\Videos\\Desktop\\Desktop 2024.10.20 - 16.03.16.04.mp4
C:\\Users\\mgrr\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\Desktop 2024.10.20 - 16.03.16.04.lnk
C:\\Users\\mgrr\\Videos\\Desktop\\Desktop 2024.10.20 - 16.03.16.04.mp4
C:\\Users\\mgrr\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\Desktop 2024.10.20 - 16.03.16.04.lnk
C:\\Users\\mgrr\\Videos\\Desktop\\Desktop 2024.10.20 - 16.03.16.04.mp4
C:\\Users\\mgrr\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\Desktop 2024.10.20 - 16.03.16.04.lnk

Execution time: 94.0131 seconds
c++ performance optimization
1个回答
0
投票

在这种情况下,系统化的方法对于识别代码中的瓶颈至关重要。您可以使用 C++ 分析工具来查明代码的哪些部分导致速度变慢。 Visual Studio 包含内置的 C++ 分析器,或者您可以从此处列出的其他选项中进行选择:

您最喜欢的分析工具是什么(针对 C++)

此外,YouTube 上还有很多关于 C++ 代码分析的教程。一旦确定了一个或多个瓶颈,您就可以通过优化现有代码或实施多线程等解决方案来解决它们。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.