Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using putchar_unlocked for fast output

Tags:

c++

I wish to use fast input and output in my code. I understood the use of getchar_unlocked for fast input using the below function.

inline int next_int() {
    int n = 0;
    char c = getchar_unlocked();
    while (!('0' <= c && c <= '9')) {
        c = getchar_unlocked();
    }
    while ('0' <= c && c <= '9') {
        n = n * 10 + c - '0';
        c = getchar_unlocked();
    }
    return n;
}

can someone please explain me how to use fast output using putchar_unlocked() function?

I was going through this question and there someone said putchar_unlocked() could be used for fast output.

like image 796
Tilak Raj Singh Avatar asked Aug 02 '13 00:08

Tilak Raj Singh


People also ask

Is Getchar faster?

It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general.

Is Getchar faster than CIN?

putchar() / getchar() work about 2-3 times faster than cout / cin for character input/output.

How do you take fast input?

It is often recommended to use scanf/printf instead of cin/cout for fast input and output. However, you can still use cin/cout and achieve the same speed as scanf/printf by including the following two lines in your main() function: ios_base::sync_with_stdio(false);

What is fast input output in CPP?

Fast input and output in C++ In competitive programming fast execution, input and outputs matter a lot. Sometimes we need to enter only five numbers in the array and the other time there can be 10,000. These are the cases where fast I/O comes into the picture.


1 Answers

Well the following code works well for fast output using putchar_unlocked().

  #define pc(x) putchar_unlocked(x);
    inline void writeInt (int n)
    {
        int N = n, rev, count = 0;
        rev = N;
        if (N == 0) { pc('0'); pc('\n'); return ;}
        while ((rev % 10) == 0) { count++; rev /= 10;} //obtain the count of the number of 0s
        rev = 0;
        while (N != 0) { rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;}  //store reverse of N in rev
        while (rev != 0) { pc(rev % 10 + '0'); rev /= 10;}
        while (count--) pc('0');
    }

Normally Printf is quite fast for outputs,however for writing Integer or Long Outputs,the below function is a tad bit faster.
Here we use the putchar_unlocked() method for outputting a character which is similar thread-unsafe version of putchar() and is faster.

See Link.

like image 138
Dhruv Chandhok Avatar answered Sep 21 '22 02:09

Dhruv Chandhok