【发布时间】:2012-10-01 14:29:39
【问题描述】:
我正在计时将文本打印到标准输出的各种方式之间的差异。我正在使用\n 和std::endl 测试cout、printf 和ostringstream。我希望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
这些结果是一致的。
【问题讨论】:
-
这可能会回答你的问题:stackoverflow.com/questions/213907/c-stdendl-vs-n 简而言之:是的,std::endl 刷新输出
-
我不知道我是否读错了这个问题,但我认为他在问为什么刷新字符串流会有性能问题。刷新字符串流有哪些额外的工作不能只留给
.str()的调用?对于cout,渲染到终端需要时间,刷新字符串流是否有任何可见的副作用? -
@stefan 我实际上已经阅读了这个问题,但部分我想知道刷新字符串流意味着什么。我认为它基本上什么都不做,但显然我错了。
-
@stefan 我用 O3 优化过,每种方法的相对效率是一样的。
-
@bames53 好问题。 g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
标签: c++ performance flush stringstream ostream