使用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 然后 重定向 日志 cout 输出 ofstream 速度 使用      更新时间:2023-10-16

我可以使用将数据写入文件

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