【发布时间】:2019-09-16 14:34:34
【问题描述】:
我有一个应用程序必须遍历每个字符(以检查一些特殊情况)并使用 ostream put 方法将其写入流。
当 ostream* 指向文件流时,它的执行速度比 ostream* 指向被重定向到文件的 cout 时快得多。
在这个 (https://stackoverflow.com/a/1697906/12074577) 答案中,我看到使用 fstream 可能会更快,因为与 cout 相比,缓冲层多了一层。 我以为当我知道输出要到 cout 时,我可以通过一个字符串缓冲区,当缓冲区已满时,将其附加到 cout。 这样我获得了另一层缓冲,性能会有所提高。
所以我这里有一个写 3200 万行的测试,每行是一个十个字符的字符串。 我使用 cout、fstream 和 stringbuffer 编写它们,后来附加到 cout。
void print_to_ostream(ostream *out, string& ones)
{
for (int i = 0; i < 32000000; ++i){
const char* ones_char = ones.c_str();
for (int j = 0; j < ones.size(); ++j ){
out->put(ones_char[j]);
}
}
}
int main(void){
string ones ="1111111111";
ostream *out = &cout;
size_t cout_time = 0;
size_t file_time = 0;
size_t cout_buffered_time = 0;
// print cout using ostream
mono_tick_timer time;
print_to_ostream(out, ones);
cout_time += time.tick();
// write to file using ostream
ofstream file("/tmp/test_file");
out = &file;
time.tick();
print_to_ostream(out, ones);
file_time += time.tick();
// ***optional solution***
// print to cout but passing through a string buffer
stringstream buffer;
out = &buffer;
time.tick();
print_to_ostream(out, ones);
cout_buffered_time += time.tick();
cout << buffer.str();
size_t buf_to_cout = time.tick();
std::cerr << "cout time: " << (double)cout_time / 1e6 << endl;
std::cerr << "file time: " << (double)file_time / 1e6 << endl;
std::cerr << "cout buffered time: " << (double)cout_buffered_time / 1e6 << endl;
std::cerr << "buf_to_cout: " << (double)buf_to_cout / 1e6 << endl;
return 0;
}
运行./a.out > /tmp/test_times的结果
如下(毫秒):
cout time: 4773.62
file time: 2391.52
cout buffered time: 2380.83
buf_to_cout: 131.615
我的底线问题是:在将所有内容附加到 cout 之前使用 stringstream 作为缓冲区是一个好的解决方案吗? 考虑到有时 cout 被重定向到一个文件的大输出,有时它只是被打印到控制台?
这些解决方案是否有我没有想到的负面影响? 还是有更好的我没想到的?
【问题讨论】:
-
也许添加一个
buffer <<std::flush()并将其包含在最终案例的时间安排中。您的数据可能仍在内存中。