7

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.

Community
  • 1
  • 1
Tilak Raj Singh
  • 353
  • 2
  • 5
  • 15

1 Answers1

9

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.

ArekBulski
  • 4,520
  • 4
  • 39
  • 61
Dhruv Chandhok
  • 780
  • 7
  • 18