簡體   English   中英

C++ vs Python vs Ruby 在遞歸列出所有目錄中的性能

[英]C++ vs Python vs Ruby Performance in Listing All Directories Recursively

我剛剛編寫了一個 C++ 代碼來遞歸列出文件夾中的所有目錄。 我正在使用 Boost 文件系統,並且靜態構建了以下代碼:

#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
using namespace std;

int main(int argc, char* argv[]) {
    const path current_file_path(current_path());

    try {
        std::vector<path> directories_vector;
        for (auto&& x : recursive_directory_iterator(current_file_path))
            if (is_directory(x.path()))
                directories_vector.push_back(x.path());
        /* GETTING UP TO HERE TAKES MORE TIME THAN PYTHON OR RUBY*/

        for (auto&& x : directories_vector) {
            cout << x << '\n';
        }
    }
    catch (const filesystem_error& ex) {
        cout << ex.what() << '\n';
    }

    cin.get();
    return 0;
}

我想看看這段代碼在 Python 和 Ruby 上的運行速度有多快。 我知道與 I/O 相關的東西不適合評估代碼性能,但是當我運行 C++ 可執行文件時,15 個以上的遞歸文件夾需要將近 3 秒的時間,而以下 Python 和 Ruby 代碼幾乎立即運行:

紅寶石:

Dir.glob("**/*/")

Python:

[x[0] for x in os.walk(directory)]

所有代碼都在 SSD 上運行。 我在 Windows 上使用 Visual Studio 2017、Python 3.5.2 和 Ruby 2.4。 C++ 代碼使用 Release/x64 模式,優化設置為最大優化(支持速度)(/O2)。

為什么 C++ 代碼在面對大量遞歸文件夾時會變慢?

通過使用strace運行 C++ 版本和 Ruby 版本,我們可以得到一些線索,為什么 C++ 版本更慢。

使用Linux源代碼進行測試(65000個文件):

strace -o '|wc' cpp_recursion
  86417  518501 9463879

strace -o '|wc' ruby -e 'Dir.glob("**/*")' 
  30563  180115 1827588

我們看到 C++ 版本執行的操作幾乎是 Ruby 的 3 倍。

更仔細地查看 strace 輸出,您會發現兩個程序都使用getdents來檢索目錄條目,但 C++ 版本對每個文件都運行lstat ,而 Ruby 版本則不然。

我只能得出結論,C++ 版本的實現效率不如 Ruby 版本(或者它可能用於不同的目的)。 速度差異不是語言問題,而是實現問題。

NB 帶-O優化的C++ 版本運行時間為0.347s,而Ruby 版本運行時間為0.304s。 至少在 Linux 上lstat似乎不會產生太多開銷。 也許 Windows 上的情況有所不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM