Fast input output function

#define getcx getchar_unlocked inline void inp( int &n )//fast input function { n=0; int ch=getcx();int sign=1; while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getcx();} while( ch >= '0' && ch <= '9' ) n = (n<<3)+(n<<1) + ch-'0', ch=getcx(); n=n*sign; } 

Hi, I used the above function to enter in various coding contests, but I still could not understand why this is happening fast. I know the logic, but I don’t know the concept of its stability. For example, what is this line: #define getcx getchar_unlocked. In addition, I do not know any quick output function, so there is a quick exit function.

+5
source share
3 answers

#define uses a preprocessor to make getcx short hand for the getchar_unlocked() function, which is a non-commit character lock function.

It's a little surprising that you participated in several coding contests without understanding this pretty basic part of C.

The manual page I linked to above mentions putc_unlocked() , which sounds putc_unlocked() much the same as for output.

+3
source

getchar_unlocked() is an unsafe version of the getchar() stream. The reason that getchar_unlocked() seems to be faster is because it does not check for any locks on the input stream where the character is supposed to get from. Therefore, if another thread has blocked the input stream, this thread must wait until the block count reaches zero . But this function does not care about this, thereby destroying synchronization between threads.

But if you are sure that the lack of synchronization will not harm you, then this function can help you a little faster.

He was also advised that you can only use it safely when the calling thread has blocked stdin using flockfile () (or ftrylockfile() ).

+3
source

Define a macro called getcx so that it does not use locks when reading. This is not thread safe, but faster if you are not worried about thread safety:

 #define getcx getchar_unlocked 

Define inp as inline to make it faster:

 inline void inp( int &n )//fast input function { n=0; int ch=getcx();int sign=1; while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getcx();} 

Multiply n by 10 (using the shift to compute 8 * n + 2 * n, which could be faster):

  while( ch >= '0' && ch <= '9' ) n = (n<<3)+(n<<1) + ch-'0', ch=getcx(); n=n*sign; } 

You can use putchar_unlocked to have a faster output function if thread safety is not an issue.

+2
source

Source: https://habr.com/ru/post/950864/


All Articles