简体   繁体   English

正在使用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

I can write data to a file using 我可以使用将数据写入文件

std::ofstream fileStream;
fileStream << "Some Data";

or simply do a 或者只是做一个

std::cout << "Some Data";

and do ./myBinary > outFile 并执行./myBinary > outFile

Which one is faster ? 哪一个更快?

It should not be significantly slower, and in fact the performance difference (if there even is any!) will be negligible. 它不会显着变慢,实际上,性能差异(即使有的话!)可以忽略不计。

Redirection causes the standard output / input / error handles to be replaced with a handle directly to the given file. 重定向导致将标准输出/输入/错误句柄替换为直接指向给定文件的句柄。 As long as there are not needless flushes of the output stream, performance should be nearly identical, if not exactly identical. 只要没有不必要的输出流刷新,性能就应该几乎相同,即使不是完全相同。 (I would hope that std::cin is able to detect whether or not output is to a terminal, and disable automatic flushing on std::endl if it is not.) (我希望std::cin能够检测输出是否到终端,如果不是,则禁用std::endl上的自动刷新。)

To prove this, let's take this small C program: 为了证明这一点,让我们看一下这个小的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;
}

And run it in a few situations: 并在几种情况下运行它:

chris@onslow:~$ ./testbin
Output is file? 0
chris@onslow:~$ ./testbin >/dev/null
Output is file? 0
chris@onslow:~$ ./testbin >foo
Output is file? 1

With a similar program that calls fstat() on standard input, we can see that the program can determine the size of the input file, indicating that it has a handle directly to the file and not some intermediate pipe: 使用类似的在标准输入上调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM