I tested the performances of fscanf
and ifstream
in reading the words from a file. While fscanf
performs a little better than ifstream
, I don't think it warrants a change of strategy. I am assuming that the relative performances of scanf
and cin
will be very similar.
My test platform: Linux, g++ 4.8.4.
File contents when run wc
on it:
>> wc socc.in
321 1212 7912 socc.in
Relative performances:
Time taken: 0.894997 (using ifstream)
Time taken: 0.724011 (using fscanf)
Program used:
#include <cstdio>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
void test1(std::string const& filename)
{
std::ifstream infile(filename);
if ( !infile )
{
return;
}
// Extract the words from the file using an ifstream.
std::string a;
while ( infile >> a );
}
void test2(std::string const& filename)
{
FILE* infile = fopen(filename.c_str(), "r");
if ( infile == NULL )
{
return;
}
// Extract the words from the file using an ifstream.
// I know that my file does not have any word longer
// than 999 characters.
char word[1000];
while ( fscanf(infile, "%s", word) == 1 );
fclose(infile);
}
void repeat(void (*fun)(std::string const&),
int count,
std::string const& filename)
{
for ( int i = 0; i < count; ++i )
{
fun(filename);
}
}
void timeFunction(void (*fun)(std::string const&),
int count,
std::string const& filename)
{
clock_t start = std::clock();
repeat(fun, count, filename);
clock_t end = std::clock();
double secs = 1.0*(end-start)/CLOCKS_PER_SEC;
std::cout << "Time taken: " << secs << std::endl;
}
int main(int argc, char** argv)
{
int count = std::atoi(argv[1]);
char* filename = argv[2];
timeFunction(test1, count, filename);
timeFunction(test2, count, filename);
}
Program execution and output:
>> ./socc 10000 socc.in
Time taken: 0.894997
Time taken: 0.724011