gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:31:19 30 4
gpt4 key购买 nike

我正在计算将文本打印到标准输出的各种方式之间的差异。我正在使用 \nstd::endl 测试 coutprintfostringstream 。我预计 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

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

关于为什么 flush 甚至对 ostringstream(不应发生刷新)也有性能影响:似乎至少需要一个实现来构造哨兵对象。那些需要检查 ostreamgoodtie。对 pubsync 的调用应该能够被优化掉。这是基于我对 libcpp 和 libstdc++ 的阅读。

阅读更多内容后,有趣的问题似乎是:basic_ostringstream::flush 的实现是否真的需要构造哨兵对象?如果不是,这对我来说似乎是一个“实现质量”问题。但我实际上认为它需要这样做,因为即使是 basic_stringbug 也可以更改以设置其 badbit

关于c++ - 为什么将 std::endl 与 ostringstream 一起使用会影响输出速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12675273/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com