Explain Faster I/O Method

Im Also Interested to Use Faster I/O methos in my programme.When I had gone through some solutions I have seen this code snippet in most of them used for fast input and fast output

Can Anyone explain me these functions clearly and how they are improving our running time??

inline void fastRead(int *a)
{
register char c=0;
while (c<33) c=getchar_unlocked();
*a=0;
while (c>33)
{
*a=*a*10+c-'0';
c=getchar_unlocked();
}
}
inline void fastWrite(int a)
{
register char c;
char snum[20];
int i=0;
do
{
snum[i++]=a%10+48;
a=a/10;
}while(a!=0);
i=i-1;
while(i>=0)
putchar_unlocked(snum[i--]);
putchar_unlocked('\n');
}
2 Likes

[getchar_unlocked()][1] is the thread unsafe version of [getchar()][2]. 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.

Speed Comparison :

getchar_unlocked > getchar > scanf > cin

Unless speed factor is too much necessary, try to avoid getchar_unlocked.
[1]: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getchar_unlocked.html
[2]: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getchar.html

EDIT:
Standard I/O functions need to lock mutexes and prevent simultaneous access to input buffer, that is why is they are thread safe. Unlocked versions of these functions do not set locks themselves, and do not test for the presence of locks set by others, thus decreasing overhead of mutual exclusion. These functions may be used to avoid the overhead of locking the stream for each character, and to avoid input being dispersed among multiple threads reading from the same stream.

Hope it helps, Best Luck :slight_smile:

1 Like

"it doesn’t check for any locks on the input stream from where it is supposed to fetch a character.
"

eleborate this please

The Terminology U used was way tooo difficult for beginners like me to understand :frowning: :frowning:

I Understood absolutely nothing… mutexes,inputbuffer,thread safe uffff :frowning: :frowning: I must search almost all the words in google :smiley:

2 Likes

Same Doubt :frowning: Understood nothing :wink: