I conjectured that ifstream
would be faster than fscanf
because fscanf
has to parse the format string every time it runs, whereas, with ifstream
, we know at compile time what kind of "thing" we want to read.
But when I ran this quick and dirty benchmark
#include <ctime>
#include <cstdio>
#include <iostream>
#include <fstream>
using namespace std;
#define NUMBER_OF_NUMBERS 100000000
int nums[NUMBER_OF_NUMBERS];
int main(int argc, char** argv) {
FILE * fp = fopen("nums.txt","r");
auto start = clock();
for (int i = 0; i < NUMBER_OF_NUMBERS; i++)
fscanf(fp,"%d",nums+i);
auto end = clock();
fclose(fp);
auto first = end - start;
ifstream fin("nums.txt");
start = clock();
for (int i = 0; i < NUMBER_OF_NUMBERS; i++)
fin >> nums[i];
end = clock();
fin.close();
auto second = end - start;
cout << "CLOCKS_PER_SEC : " << CLOCKS_PER_SEC << endl;
cout << "first : " << first << endl;
cout << "first (sec) : " << first / CLOCKS_PER_SEC << " seconds" << endl;
cout << "second : " << second << endl;
cout << "second (sec) : " << second / CLOCKS_PER_SEC << " seconds" << endl;
cout << "diff : " << second - first << endl;
cout << "diff (sec) : " << (second - first) / CLOCKS_PER_SEC << " seconds" << endl;
return 0;
}
I got as output the following:
CLOCKS_PER_SEC : 1000000
first : 12336249
first (sec) : 12 seconds
second : 25738587
second (sec) : 25 seconds
diff : 13402338
diff (sec) : 13 seconds
ifstream
is more than twice as slow as fscanf
. Where does fscanf
get all this speed?
EDIT:
I'm on a reasonably modern 64-bit intel mac, using command line tools that come with xcode, in case it is relevant at all.