Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading input using getchar_unlocked()

Tags:

c

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

like image 474
Neeraj Kumar Avatar asked Oct 28 '13 09:10

Neeraj Kumar


People also ask

What is the difference between getchar () and Getchar_unlocked ()?

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.

Is Getchar faster than CIN?

getchar is much faster. But it won't matter in question FUNC, because that is very tough question i think related to time optimization.


2 Answers

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 performs
n=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

like image 73
user2531723 Avatar answered Oct 02 '22 11:10

user2531723


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.

like image 43
Claudio Avatar answered Oct 02 '22 11:10

Claudio