使用std::ofstream写入文件的速度比使用std::cout慢,然后将输出重定向到日志文件
Is writing to a file using std::ofstream slower than using std::cout and then redirecting that output to a log file
我可以使用将数据写入文件
std::ofstream fileStream;
fileStream << "Some Data";
或者简单地做一个
std::cout << "Some Data";
并进行./myBinary > outFile
哪一个更快?
它应该不会明显变慢,事实上性能差异(如果有的话!)可以忽略不计。
重定向会将标准输出/输入/错误句柄替换为直接指向给定文件的句柄。只要没有不必要的输出流刷新,即使不完全相同,性能也应该几乎相同。(我希望std::cin
能够检测输出是否到终端,如果不是,则禁用std::endl
上的自动刷新。)
为了证明这一点,让我们用这个小C程序:
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat s;
fstat(fileno(stdout), &s);
fprintf(stderr, "Output is file? %dn", S_ISREG(s.st_mode));
return 0;
}
并在几种情况下运行:
chris@onslow:~$ ./testbin
Output is file? 0
chris@onslow:~$ ./testbin >/dev/null
Output is file? 0
chris@onslow:~$ ./testbin >foo
Output is file? 1
使用在标准输入上调用fstat()
的类似程序,我们可以看到该程序可以确定输入文件的大小,这表明它有一个直接指向文件的句柄,而不是一些中间管道:
chris@onslow:~$ ./testbin
Input file size is 0
chris@onslow:~$ ./testbin < /dev/null
Input file size is 0
chris@onslow:~$ echo hello > foo
chris@onslow:~$ ./testbin < foo
Input file size is 6
相关文章:
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 如何传递多个 std::文件系统选项?
- 遍历顺序由 std::文件系统directory_iterator给出
- 使 std::fstream 写入文件末尾,但从头开始读取
- 是否可以使用 Python csv 阅读器读取使用 C++ std::setw 生成的文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++ VS 错误:<实验/文件系统>提供 std::experimental::文件系统的标头已被Microsoft弃用,将被删除
- 'generate'不是窗口头文件中'std::random_device'的成员<random>
- Windows std::fstream 修改文件后打开()?
- 是否可以使用 std::文件系统获取根名称列表?
- 如何将文件的一部分读取到std::list缓冲区?
- llvm 9在10.15之前的mac版本上支持std::文件系统吗
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 当 ofstream 指针位于 std::map 中时,文件写入不会发生 C++.
- std(boost)::文件系统::p ath 组件数
- 变量 std::fstream 文件具有初始值设定项,但类型不完整 编译错误
- std::文件系统根路径如何将自身作为父路径?
- 为什么我打开一个没有std::ios::binary的文件(std::ifstream)