Fast input output function

偶尔善良 提交于 2019-12-04 07:25:10

getchar_unlocked() is the thread unsafe version of getchar()The reason that getchar_unlocked() seems faster is that it doesn't check for any locks on the input stream from where it is supposed to fetch a character. So if another thread has locked the input stream, this thread is supposed to wait till lock count has come to zero. But this function doesn't care about it, thereby destroying synchronisation between threads.

But if you are sure that lack of synchronisation wont harm you, then this function might help you to be a bit faster.

Also, its advised that you can use it safely only when the invoking thread has locked stdin using flockfile() (or ftrylockfile()).

unwind

The #define uses the preprocessor to make getcx be a short-hand for the function getchar_unlocked(), which is a non-locking character-reading function.

It's a bit awesome that you've competed in several coding contests without understanding this pretty basic piece of C.

The manual page I linked to above mentions putc_unlocked() which sounds like pretty much the same thing but for output.

Define a macro called getcx such that no locks will be used while reading. This is not thread safe but faster if you are not worried about thread safety:

#define getcx getchar_unlocked

Define inp as inline so that it is 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 shift to compute 8*n+2*n, which might 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 when thread safety is not an issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!