Outputting an inverted index to a text file When I run this function for outputting an inverted index to a text file in Debug Configuration, it takes nearly two minutes (96 seconds) with a comparatively tiny dataset, 1252 records with the longest being 76 entries.

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out_stream, const InvertedIndex&amp; rhs) {
    std::ostringstream output_buffer;
    auto&amp; rhs_index = rhs.GetIndex();
    for(auto map_elem : rhs_index) {
        output_buffer &lt;&lt; map_elem.first;
        auto&amp; cur_postingset = map_elem.second;
        for(auto set_elem : cur_postingset) {
            output_buffer &lt;&lt; " &lt;" &lt;&lt; set_elem.GetDocumentId() &lt;&lt; ' ' &lt;&lt; set_elem.GetTokenFrequency() &lt;&lt; "&gt;";
        }
        output_buffer &lt;&lt; '\n';
    }
    output_buffer.flush();
    out_stream.write(output_buffer.str().c_str(), output_buffer.str().size());
    return out_stream;
}


The index is a std::map&lt;std::string, std::vector&lt;std::pair&lt;unsigned long, std::string&gt;&gt;&gt; data type. It makes debugging other portions of the program tedious and time-consuming. Is there any way to speed it up or am I going to have to live with it?
In main add:

std::ios_base::sync_with_stdio(false); //   do not keep the C and C++ streams synced.
                                       //   No extra works make this quicker.


The quickest way to flush one stream into another is:

stream &lt;&lt; otherStream.rdBuf();


So rather than this:

out_stream.write(output_buffer.str().c_str(), output_buffer.str().size());

// prefer
out_stream &lt;&lt; output_buffer.rdBuf();


The other things that slows things down is excessive flushing. Don't flush your stream until you really want the output (so its not good practice to flush the stream while you are writing to it). Do it explicitly afterwords.

out_stream &lt;&lt; object &lt;&lt; std::flush;


But I see no reason for copying all the data into one stream then re-copying the data into another stream.

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out_stream, const InvertedIndex&amp; rhs)
{
    auto&amp; rhs_index = rhs.GetIndex();
    for(auto map_elem : rhs_index) {
        out_stream &lt;&lt; map_elem.first;
        auto&amp; cur_postingset = map_elem.second;
        for(auto set_elem : cur_postingset) {
            out_stream &lt;&lt; " &lt;" &lt;&lt; set_elem.GetDocumentId() &lt;&lt; ' ' &lt;&lt; set_elem.GetTokenFrequency() &lt;&lt; "&gt;";
        }
        out_stream &lt;&lt; '\n';
    }
    return out_stream;
}