What is most efficient way to read a file of integer in each line without opening it?
I have a file with ONLY integer in each line, ie: num.txt
100
231
312
...
In my program, I use while loop to read it;
int input = 0;
while(cin >> input)
{
// Assignment
}
I use time a.out
It turns out that it will take about 15 second (user time) to read 100 million numbers. So I was wondering is there any better way to decrease user time?
Thank you in advance!
Answer
int input = 0;
ios_base::sync_with_stdio(false);
//Add this statement and see the magic!
while(cin >> input)
{
// Assignment
}
To make it ultra fast (Not recommended for assignments!), use getchar_unlocked()
:
int read_int() {
char c = getchar_unlocked();
while(c<'0' || c>'9') c = gc();
int ret = 0;
while(c>='0' && c<='9') {
ret = 10 * ret + c - 48;
c = getchar_unlocked();
}
return ret;
}
int input = 0;
while((input = read_int()) != EOF)
{
// Assignment
}
Vaughn Cato's answer explains it beautifully.
No comments:
Post a Comment