Fast input output function

此生再无相见时 提交于 2019-12-06 02:45:33

问题


#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 have been using the above function for input in various coding contests but was never able to understand why is it fast. I know the logic but don't know the concept of it's fastness. For example what is this line doing "#define getcx getchar_unlocked" . Also I don't know any fast output function so is there any fast output function also


回答1:


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()).




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/12073617/fast-input-output-function

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