# Speed of taking two space separated integers

Here is a code of function scan, which accepts space separated integers,
how can i make this code more efficient? One which takes less time.

``````int scan(){
int t=0;
char c;
c=getchar_unlocked();
while(c<'0' || c>'9')
c=getchar_unlocked();
while(c>='0' && c<='9'){
t=(t<<3)+(t<<1)+c-'0';
c=getchar_unlocked();
}
return(t);
}
``````

Daksh

@cprgdaksh

You can make a bufffer

`char ibuf[1<<26] //1 mb input buffer`

and then you can read the whole input at once using `fread` Thats what i do.

``````#define BUFSIZE (1<<26)
char IBUF[BUFSIZE+1];
#define INPUT fread(IBUF, 1, BUFSIZE, stdin);
``````

Then you can use array IBUF to read anything. and remember that the IBUF array has exactly same format of input as in stdin

if stdin input is

``````3 5
3 4
4 5
5 6
``````

then

``````IBUF[0]=='3';
IBUF[1]==' ';
IBUF[2]=='5';
IBUF[3]=='\n'
``````

Here is an getInt implementation.

``````#define INPUT fread(IBUF, 1, BUFSIZE, stdin);
#define BUFSIZE (1<<26)
char IBUF[BUFSIZE+1], *inputptr=IBUF;
#define DIG(a) (((a)>='0')&&((a)<='9'))
#define getChar(t) {t=*inputptr++;}
template<class T>inline bool getInt(T &j)
{
j=0;
int _t;
getChar(_t);
if(_t==0)return false;
char sign;
while(!DIG(_t)&&_t!=0)
{
sign=_t;
getChar(_t);
}
while(DIG(_t))
{
j=10*j+(_t-'0');
getChar(_t);
}
if(sign == '-') j = -j;
*inputptr--;
return j==0&&_t==0?false:true;
}
``````

And then your main function will look like;

``````int main()
{
INPUT; //for copying from stdin to input buffer
int t,k;
getInt(k);
printf("%d %d",t,k);
return 0;
}
``````

In the same way you can define getString etc functions. and also you can provide OUTPUT BUFFER to copy the output to output buffer and then write all at once at stdout.
This implementation take some memeory but is very fast.

Reason is that when we read input from scanf they open the stream take input then lock the stream everytime this locking and unlocking takes excess time… Thats why getchar_unlocked is used by coders here.

Also if you want to work on Fast I/O you can work on the problem [INTEST][1] You can read people’s codes there and work on your input output.

One of the best Implementations of CIN/COUT in c++ that I have seen is suggested by @mukel .The [link is here][2] . Hope that helps now Enjoy

P.S: The above implementation will work in c++
[1]: http://www.codechef.com/problems/INTEST
[2]: http://discuss.codechef.com/questions/6677/cool-fast-io-implementation

1 Like

your code will work fine and fast for integer iinput

@amitupadhyay: If it, is like 4324 4312.
Then?
and i need them as integers.