我想测试在 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 脚本这么慢?
最佳答案
有几个原因。
首先,解释执行环境(如 bash
、perl
以及非 JITed lua
和 python
等)通常比编写不佳的编译程序(C
、C++
等)慢得多。
其次,请注意您的 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++ 中实现流以及为什么 \n
与 endl
不同的更多信息,请参阅有关 C++ 的任何引用文档。
第三,正如评论所证明的那样,您的 bash 脚本为每一行执行目标文件的打开/关闭。这本身就意味着显着的性能开销 - 想象 myfile.open
和 myfile.close
移动到您的循环体内!
关于C++ 比写入文本文件的 Bash 脚本快得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912276/