为什么将 std::endl 与 ostringstream 一起使用会影响输出速度?

2024-05-25

我正在计算将文本打印到标准输出的各种方法之间的差异。我正在测试cout, printf, and ostringstream两者同时使用\n and std::endl。我期望std::endl有所作为cout(确实如此),但我没想到它会减慢输出速度ostringstream。我想用std::endl只会写一个\n到流中,它仍然只会被刷新一次。这里发生了什么?这是我的全部代码:

// cout.cpp
#include <iostream>

using namespace std;

int main() {
  for (int i = 0; i < 10000000; i++) {
    cout << "Hello World!\n";
  }
  return 0;
}

// printf.cpp
#include <stdio.h>

int main() {
  for (int i = 0; i < 10000000; i++) {
    printf("Hello World!\n");
  }
  return 0;
}

// stream.cpp
#include <iostream>
#include <sstream>

using namespace std;

int main () {
  ostringstream ss;
  for (int i = 0; i < 10000000; i++) {
    ss << "stream" << endl;
  }
  cout << ss.str();
}

// streamn.cpp
#include <iostream>
#include <sstream>

using namespace std;

int main () {
  ostringstream ss;
  for (int i = 0; i < 10000000; i++) {
    ss << "stream\n";
  }
  cout << ss.str();
}

这是我的 Makefile

SHELL:=/bin/bash

all: cout.cpp printf.cpp
    g++ cout.cpp -o cout.out
    g++ printf.cpp -o printf.out
    g++ stream.cpp -o stream.out
    g++ streamn.cpp -o streamn.out
time:
    time ./cout.out > output.txt
    time ./printf.out > output.txt
    time ./stream.out > output.txt
    time ./streamn.out > output.txt

这是我跑步时得到的结果make其次是make time

time ./cout.out > output.txt

real    0m1.771s
user    0m0.616s
sys 0m0.148s
time ./printf.out > output.txt

real    0m2.411s
user    0m0.392s
sys 0m0.172s
time ./stream.out > output.txt

real    0m2.048s
user    0m0.632s
sys 0m0.220s
time ./streamn.out > output.txt

real    0m1.742s
user    0m0.404s
sys 0m0.200s

这些结果是一致的。


std::endl触发流的刷新,这会大大减慢打印速度。看http://en.cppreference.com/w/cpp/io/manip/endl http://en.cppreference.com/w/cpp/io/manip/endl

通常建议不要使用std::endl除非你真的想要刷新流。如果这对您真的很重要,则取决于您的用例。

至于为什么flush即使在 ostringstream 上也会对性能产生影响(不应发生刷新):似乎至少需要一个实现来构造哨兵对象。那些需要检查good and tie of the ostream。致电给pubsync应该可以优化掉。这是基于我对 libcpp 和 libstdc++ 的阅读。

经过更多阅读后,有趣的问题似乎是:是basic_ostringstream::flush真的需要构造哨兵对象吗?如果不是,这对我来说似乎是一个“实施质量”问题。但我实际上认为有必要这样做,因为即使是basic_stringbug可以改变有它的badbit set.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么将 std::endl 与 ostringstream 一起使用会影响输出速度? 的相关文章

随机推荐