c++cprintfcoutputchar

Why this approach using putchar_unlocked is slower than printf and cout to print strings?


I'm studying manners of speedup my algorithms for programming's contests, using as base the acceleration of input and output processing.

I'm currently using the thread-unsafe putchar_unlocked function to print in some evaluations. I've thought that this function was faster than cout e printf to some data types if well implemented due to its thread-unsafe nature.

I had implemented a function to print strings in this way (IMHO very simple):

void write_str(char s[], int n){
    int i;
    for(i=0;i<n;i++)
        putchar_unlocked(s[i]);
}

I tested with a string of size n and exactly n characters.
But it is the slowest of the three, as we can see in this chart of number of output writes versus time in seconds: Graph

Why it is the slowest?


Solution

  • Choosing the faster way to output strings comes into conflict with the platform, operating system, compiler settings and runtime library in use, but there are some generalizations which may help understand what to select.

    First, consider that the operating system may have a means of display strings as compared to characters one at a time, and if so, looping through a system call for character output one at a time would naturally invoke overhead for every call to the system, as opposed to the overhead of one system call processing a character array.

    That's basically what you're encountering, the overhead of a system call.

    The performance enhancement of putchar_unlocked, compared to putchar, may be considerable, but only between those two functions. Further, most runtime libraries do not have putchar_unlocked (I find it on older MAC OS X documentation, but not Linux or Windows).

    That said, locked or unlocked, there would still be overhead for each character that may be eliminated for a system call processing the entire character array, and such notions extend to output to files or other devices, not just the console.