I have learnt that using getchar_unlocked
is fast way of reading input. I have seen the code to read at many places but was unable to understand. Can anyone please help me understand how to read using getchar_unlocked
?
Thanks in Advance.
void scanint(int &x)
{
register int c = getchar_unlocked();
x = 0;
for(;(c<48 || c>57);c = getchar_unlocked())
;
for(;c>47 && c<58;c = getchar_unlocked())
{
x = (x<<1) + (x<<3) + c - 48;
}
}
I have seen many other codes as well. I dont particularly understand the purpose of shifting the number. Any help regarding that is appreciated
One more difference with getchar() is, it is not a C standard library function, but a POSIX function. It may not work on Windows-based compilers. It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general. getchar_unlocked() is faster than getchar(), hence fastest of all.
getchar is much faster. But it won't matter in question FUNC, because that is very tough question i think related to time optimization.
getch_lock
reads a character at a time. here in the given code we are trying to read an integer. the purpose of first for
loop is to read digit character if any present and neglect it. The second for
loop reads a char which must be digit and performsn=n*10+c
As C is in Ascii we have subtracted 48 ie Ascii code of '0'
. To make code faster instead of using multiplication shift is used.n*10=n*(8+2)=n*8+n*2=n<<3+n<<1
getchar_unlocked()
is like getchar()
except that it does not check for multi-thread locks.
So, it is faster, but it is not thread-safe.
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