I am trying to benchmark the effects of manual buffering (via std::stringbuf
) on the running time while performing a write to a file as opposed to buffering done by the insertion operator <<
.
Version 1 (without manual buffering)
This version involves performing a write at each iteration.
std::ofstream ofs;
ofs.open("output_file", std::ios::out);
for (int i = 0; i < 100000000; i++)
ofs << "Hello world!\n";
Time: 2.83s user 1.14s system 28% cpu 13.918 total
Version 2 (with manual buffering)
This version buffers the entire data in std::string
object before finally writing it.
std::string buffer;
std::ofstream ofs;
ofs.open("output_file", std::ios::out);
for (int i = 0; i < 100000000; i++)
buffer.append("Hello world!\n");
ofs << buffer;
Time: 1.87s user 2.27s system 24% cpu 16.654 total
There is an observable difference between the running times of version 1 and 2, and similar behavior was observed in different runs. How is it the case that the second version ends up being slower when it only performs a single write operation as opposed to multiple writes in first ?
This result is also in contrast with the results posted in a previous question, however the current case is a slight variation of that.