[英]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? %d\n", 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.