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.
It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general.
putchar() / getchar() work about 2-3 times faster than cout / cin for character input/output.
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With