简体   繁体   中英

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

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.)

To prove this, let's take this small C program:

#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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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