Hmm... I just timed the 3 methods and it looks like the first is the fastest:
Code:
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;
void Test1( ifstream& file )
{
string line;
while ( !file.eof() )
{
getline( file, line );
// cout << line << endl;
}
}
void Test2( ifstream& file )
{
string line;
while ( file >> line )
{
// stringstream os( line );
// cout<<line;
}
}
void Test3( ifstream& file )
{
string fileData( (istreambuf_iterator<char>( file )),
istreambuf_iterator<char>() );
}
typedef void (*TestFunc)( ifstream& );
clock_t TimeFunc( TestFunc func, const char* filename )
{
ifstream file( filename );
clock_t start = clock();
func( file );
clock_t end = clock();
return (end - start);
}
int main()
{
for ( int i = 0; i < 10; ++i )
{
clock_t time1 = TimeFunc( &Test1, "E:/Test_10MB.txt" );
clock_t time2 = TimeFunc( &Test2, "E:/Test_10MB.txt" );
clock_t time3 = TimeFunc( &Test3, "E:/Test_10MB.txt" );
cout << endl << "Func1() time is: " << time1
<< endl << "Func2() time is: " << time2
<< endl << "Func3() time is: " << time3 << endl;
}
return 0;
}
Code:
Func1() time is: 890
Func2() time is: 1297
Func3() time is: 1125
Func1() time is: 843
Func2() time is: 1266
Func3() time is: 1125
Func1() time is: 875
Func2() time is: 1282
Func3() time is: 1109
Func1() time is: 875
Func2() time is: 1281
Func3() time is: 1125
Func1() time is: 844
Func2() time is: 1281
Func3() time is: 1125
Func1() time is: 860
Func2() time is: 1265
Func3() time is: 1141
Func1() time is: 843
Func2() time is: 1282
Func3() time is: 1125
Func1() time is: 875
Func2() time is: 1265
Func3() time is: 1110
Func1() time is: 844
Func2() time is: 1297
Func3() time is: 1109
Func1() time is: 859
Func2() time is: 1266
Func3() time is: 1125