Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast C++ String Output

I have a program that outputs the data from an FPGA. Since the data changes EXTREMELY fast, I'm trying to increase the speed of the program. Right now I am printing data like this

for (int i = 0; i < 100; i++) {
    printf("data: %d\n",getData(i));
}

I found that using one printf greatly increases speed

printf("data: %d \n data: %d \n data: %d \n",getData(1),getData(2),getData(3));

However, as you can see, its very messy and I can't use a for loop. I tried concatenating the strings first using sprintf and then printing everything out at once, but it's just as slow as the first method. Any suggestions?

Edit: I'm already printing to a file first, because I realized the console scrolling would be an issue. But its still too slow. I'm debugging a memory controller for an external FPGA, so the closer to the real speed the better.

like image 606
woojoo666 Avatar asked Aug 23 '13 21:08

woojoo666


1 Answers

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 untie 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);
}
like image 50
sehe Avatar answered Sep 25 '22 19:09

sehe