Fast C++ String Output
If you are writing to stdout, you might not be able to influence this all.
Otherwise, set buffering
- setvbuf http://en.cppreference.com/w/cpp/io/c/setvbuf
- std::nounitbuf http://en.cppreference.com/w/cpp/io/manip/unitbuf
- and un
tie
the input output streams (C++) http://en.cppreference.com/w/cpp/io/basic_ios/tie std::ios_base::sync_with_stdio(false)
(thanks @Dietmar)
Now, Boost Karma is known to be pretty performant. However, I'd need to know more about your input data.
Meanwhile, try to buffer your writes manually: Live on Coliru
#include <stdio.h>
int getData(int i) { return i; }
int main()
{
char buf[100*24]; // or some other nice, large enough size
char* const last = buf+sizeof(buf);
char* out = buf;
for (int i = 0; i < 100; i++) {
out += snprintf(out, last-out, "data: %d\n", getData(i));
}
*out = '\0';
printf("%s", buf);
}
Wow, I can't believe I didn't do this earlier.
const int size = 100;
char data[size];
for (int i = 0; i < size; i++) {
*(data + i) = getData(i);
}
for (int i = 0; i < size; i++) {
printf("data: %d\n",*(data + i));
}
As I said, printf
was the bottleneck, and sprintf
wasn't much of an improvement either. So I decided to avoid any sort of printing until the very end, and use pointers instead