简体   繁体   中英

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 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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM