Originally Posted by
Daved
Would you mind testing read() and rdbuf()?
I'm not sure what you mean about rdbuf(), I've never used it, but I added Test4() using istream.read(), and I also store all lines in 1 string and then print the final string size:
Code:
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <cstdio>
#include <ctime>
using namespace std;
void Test1( ifstream& file )
{
string line;
string fileData;
while ( !file.eof() )
{
getline( file, line );
fileData += line;
}
cout << "Test1 Bytes Read: " << fileData.size() << endl;
}
void Test2( ifstream& file )
{
string line;
string fileData;
while ( file >> line )
{
fileData += line;
}
cout << "Test2 Bytes Read: " << fileData.size() << endl;
}
void Test3( ifstream& file )
{
string fileData( (istreambuf_iterator<char>( file )),
istreambuf_iterator<char>() );
cout << "Test3 Bytes Read: " << fileData.size() << endl;
}
void Test4( ifstream& file )
{
char block[BUFSIZ + 1];
string fileData;
while ( file.read( block, BUFSIZ ) )
{
fileData += block;
}
cout << "Test4 Bytes Read: " << fileData.size() << endl;
}
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()
{
const char* filename = "E:/Test_10MB.txt"; // 10,240,000 bytes
for ( int i = 0; i < 1; ++i )
{
clock_t time1 = TimeFunc( &Test1, filename );
clock_t time2 = TimeFunc( &Test2, filename );
clock_t time3 = TimeFunc( &Test3, filename );
clock_t time4 = TimeFunc( &Test4, filename );
cout << endl << "Func1() time is: " << time1
<< endl << "Func2() time is: " << time2
<< endl << "Func3() time is: " << time3
<< endl << "Func4() time is: " << time4 << endl;
}
return 0;
}
Here's the new output:
Code:
Test1 Bytes Read: 10040000
Test2 Bytes Read: 9040000
Test3 Bytes Read: 10140000
Test4 Bytes Read: 10139648
Func1() time is: 1140
Func2() time is: 3485
Func3() time is: 1296
Func4() time is: 375
Surprisingly, none of the 4 functions reports the right number of bytes (10,240,000). Does anyone know why that is? I know the >> operator doesn't extract whitespace and getline() doesn't extract the newline, but I would have expected the last two functions to store the right number of bytes.