C++ 比写入文本文件的 Bash 脚本快得多

标签 c++ linux bash

我想测试在 bash 脚本和 C++ 程序中写入文件的性能。

这是 bash 脚本:

#!/bin/bash

while true; do
        echo "something" >> bash.txt
done

这为文本文件每秒增加了大约 2-3 KB。

这是 C++ 代码:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream myfile;
    myfile.open("cpp.txt");

    while (true) {
        myfile << "Writing this to a file Writing this to a file \n";
    }

    myfile.close();
}

这在不到 10 秒的时间内创建了一个约 6 GB 的文本文件。

是什么让这个 C++ 代码这么快,和/或这个 bash 脚本这么慢?

最佳答案

有几个原因。

首先,解释执行环境(如 bashperl 以及非 JITed luapython 等)通常比编写不佳的编译程序(CC++ 等)慢得多。

其次,请注意您的 bash 代码是如何碎片化的 - 它只是将一行写入文件,然后再写入一行,依此类推。另一方面,您的 C++ 程序执行 缓冲 写入 - 即使您没有直接的努力。如果你替换它,你可能会看到它的运行速度有多慢

myfile << "Writing this to a file Writing this to a file \n";

myfile << "Writing this to a file Writing this to a file" << endl;

有关如何在 C++ 中实现流以及为什么 \nendl 不同的更多信息,请参阅有关 C++ 的任何引用文档。

第三,正如评论所证明的那样,您的 bash 脚本为每一行执行目标文件的打开/关闭。这本身就意味着显着的性能开销 - 想象 myfile.openmyfile.close 移动到您的循环体内!

关于C++ 比写入文本文件的 Bash 脚本快得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912276/

相关文章:

使用 Glib 库在 Windows 上成功构建的 C 代码在 Linux 上出现编译器/链接器错误

c - 尝试从汇编程序(64 位)的 glibc 调用 C 函数

ruby - 将 YAML 数组转换为 Bash 数组

bash - 从 bash 打开然后杀死子进程

c++ - x64 性能与 x86 相比

c++ - 模板的显式实例化

c++ - C++ 标准容器的线程安全

c++ - 如何在 C++ 中打印/检查 vector 的值

c - 文件部分用c发送

bash - 我似乎无法在 "-c"选项字符串之后使用带参数的 Bash "-c"选项