#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <sys/time.h>
using namespace std;
template <typename Func>
double benchmark(Func f, size_t iteration) {
f();
timeval a,b;
gettimeofday(&a, 0);
for (; iteration-- > 0;) {
f();
}
gettimeofday(&b, 0);
return (b.tv_sec * (unsigned int)1e6 + b.tv_sec) - (a.tv_sec * (unsigned int)1e6 + a.tv_sec);
}
class CRead {
public:
CRead(char const* filename): _filename(filename) {}
void operator()() {
FILE *file = fopen(_filename, "r");
int cnt = 0;
while (fscanf(file, "%s", _buffer) == 1) {
cnt++;
}
fclose(file);
}
private:
char const* _filename;
char _buffer[1024];
};
class CppRead {
public:
CppRead(char const* filename): _filename(filename), _buffer() {}
enum {
BufferSize = 16184
};
void operator()() {
ifstream file(_filename, ifstream::in);
file.rdbuf()->pubsetbuf(_buffer, BufferSize);
int cnt = 0;
string s;
while (file >> s) {
cnt++;
}
}
private:
char const* _filename;
char _buffer[BufferSize];
};
int main(int argc, char *argv[]) {
size_t iteration = 1;
if (argc > 1)
iteration = atoi(argv[1]);
char const* oldLocale = setlocale(LC_ALL, "C");
if (strcmp(oldLocale, "C") != 0)
cout << "Replace old locale" << oldLocale << " by C \n";
char const* filename = "large.txt";
CRead cread(filename);
CppRead cppread(filename);
bool oldSyncSetting = std::ios_base::sync_with_stdio(false);
double ctime = benchmark(cread, iteration);
double cpptime = benchmark(cppread, iteration);
std::ios_base::sync_with_stdio(oldSyncSetting);
cout << "C :" << ctime << '\n' << "C++:" << cpptime << '\n';
return 0;
}