Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;cout重定向到文件的速度比使用流的速度慢_C++_Cout_Ostream - Fatal编程技术网

C++ c++;cout重定向到文件的速度比使用流的速度慢

C++ c++;cout重定向到文件的速度比使用流的速度慢,c++,cout,ostream,C++,Cout,Ostream,我有一个应用程序,它必须迭代每个字符(检查一些特殊情况),并使用ostream put方法将其写入流 当将ostream*指向文件流时,它的执行速度比ostream*指向被重定向到文件的cout时快得多 在这个()答案中,我看到可能使用fstream会更快,因为与cout相比,它有更多的缓冲层。 我认为,当我知道输出将是cout时,我可以通过字符串缓冲区,当缓冲区已满时,将其附加到cout。 通过这种方式,我获得了另一层缓冲,性能将得到提高 我这里有一个测试,写3200万行,每行是一个10个字符

我有一个应用程序,它必须迭代每个字符(检查一些特殊情况),并使用ostream put方法将其写入流

当将ostream*指向文件流时,它的执行速度比ostream*指向被重定向到文件的cout时快得多

在这个()答案中,我看到可能使用fstream会更快,因为与cout相比,它有更多的缓冲层。 我认为,当我知道输出将是cout时,我可以通过字符串缓冲区,当缓冲区已满时,将其附加到cout。 通过这种方式,我获得了另一层缓冲,性能将得到提高

我这里有一个测试,写3200万行,每行是一个10个字符的字符串。 我使用cout、fstream和后来附加到cout的stringbuffer编写它们


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;

}

我的底线问题是:在将所有内容附加到cout之前使用stringstream作为缓冲区是一个好的解决方案吗? 考虑到这样一个事实,有时cout会被重定向到一个文件,而有时它只是被打印到控制台

它们是否有任何我没有想到的消极副作用? 或者有一个我没有想到的更好的方法?

默认情况下,全局流(例如
std::cout
)是,而
std::ofstream
不是:

默认情况下,所有八个标准C++流都与各自的C流同步。

如果同步关闭,则允许C++标准流独立地缓冲它们的I/O,在某些情况下可能会更快。


尝试使用
std::cout.sync_与_stdio(false)将其关闭

可能会添加一个
缓冲区谢谢,时差下降了一个数量级,现在是:cout time:2572.32文件时间:2500.15 cout缓冲时间:2447。
cout time: 4773.62
file time: 2391.52
cout buffered time: 2380.83
buf_to_cout: 131.615