What is the difference among these three input functions in programming language. Do they input in different ways from each other?
1.getchar_unlocked()
#define getcx getchar_unlocked
inline void inp( int &n )
{
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;
}
2.scanf("%d",&n)
3.cin>>n
Which one takes least time when input the integers?
I use THese header files in c++ where all 3 cased run in c++;
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<cassert>
With synchronization turned off, the above results indicate that cin is 8-10% faster than scanf(). This is probably because scanf() interprets the format arguments at runtime and makes use of variable number of arguments, whereas cin does this at compile time.
cin doesn't require the variable type to be added to the call to avoid this issue. scanf is typically faster than cin due to syncing. scanf and printf are a carry over from the original c programming language and use cstdio.
One more difference with getchar() is, it is not a C standard library function, but a POSIX function. It may not work on Windows-based compilers. It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general. getchar_unlocked() is faster than getchar(), hence fastest of all.
The function getchar_unlocked() is deprecated in Windows because it is a thread unsafe version of getchar(). It is suggested not to use getchar_unlocked(). There is no stream lock check that's why getchar_unlocked is unsafe. The function getchar_unlocked() is faster than getchar().
Two points to consider.
getchar_unlocked
is deprecated in Windows because it is thread unsafe version of getchar()
.
Unless speed factor is too much necessary, try to avoid getchar_unlocked
.
Now, as far as speed is concerned.
getchar_unlocked > getchar
because there is no input stream lock check in getchar_unlocked
which makes it unsafe.
getchar > scanf
because getchar
reads a single character of input which is char type whereas scanf can read most of the primitive types available in c.
scanf > cin (>> operator)
because check this link
So, finally
getchar_unlocked > getchar > scanf > cin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With