getchar_unlocked( ) VS scanf() VS cin

Anil Kumar Arya picture Anil Kumar Arya · Jan 29, 2012 · Viewed 20.4k times · Source

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>

Answer

Sobhagya Mohanty picture Sobhagya Mohanty · May 29, 2013

Two points to consider.

  1. getchar_unlocked is deprecated in Windows because it is thread unsafe version of getchar().

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