#include <cstdio>
#include <iostream>
template <typename Test>
void test (Test t)
{
const clockt begin = clock();
t();
const clockt end = clock();
std::cout << (end-begin)/double(CLOCKSPERSEC) << " sec\n";
}
void stdio() {
std::string line;
unsigned dependencyvar = 0;
while (!feof (stdin)) {
int c;
line.clear();
while (EOF != (c = fgetc(stdin)) && c!='\n')
line.push_back (c);
dependency_var += line.size();
}
std::cout << dependency_var << '\n';
}
void synced() {
std::iosbase::syncwithstdio (true);
std::string line;
unsigned dependencyvar = 0;
while (getline (std::cin, line)) {
dependencyvar += line.size();
}
std::cout << dependencyvar << '\n';
}
void unsynced() {
std::iosbase::syncwithstdio (false);
std::string line;
unsigned dependencyvar = 0;
while (getline (std::cin, line)) {
dependencyvar += line.size();
}
std::cout << dependencyvar << '\n';
}
void usage() { std::cout << "one of (synced|unsynced|stdio), pls\n"; }
int main (int argc, char *argv[]) {
if (argc < 2) { usage(); return 1; }
if (std::string(argv[1]) == "synced") test (synced);
else if (std::string(argv[1]) == "unsynced") test (unsynced);
else if (std::string(argv[1]) == "stdio") test (std_io);
else { usage(); return 1; }
return 0;
}
این کد رو تو ubuntu کامپایل کن، نتیجه این میشه:
cat testfile | ./a.out stdio
...
0.34 sec
cat testfile | ./a.out synced
...
1.31 sec
cat testfile | ./a.out unsynced
...
0.08 sec
و این کد:
#include <cstdio>
#include <iostream>
template <typename Test>
void test (Test t)
{
const clockt begin = clock();
t();
const clockt end = clock();
std::cout << (end-begin)/double(CLOCKSPERSEC) << " sec\n";
}
void scanf() {
char x,y,c;
unsigned dependencyvar = 0;
while (!feof (stdin)) {
scanf ("%c%c%c", &x, &y, &c);
dependency_var += x + y + c;
}
std::cout << dependency_var << '\n';
}
void unsynced() {
std::iosbase::syncwithstdio (false);
char x,y,c;
unsigned dependencyvar = 0;
while (std::cin) {
std::cin >> x >> y >> c;
dependencyvar += x + y + c;
}
std::cout << dependencyvar << '\n';
}
void usage() { std::cout << "one of (scanf|unsynced), pls\n"; }
int main (int argc, char *argv[]) {
if (argc < 2) { usage(); return 1; }
if (std::string(argv[1]) == "scanf") test (scanf_);
else if (std::string(argv[1]) == "unsynced") test (unsynced);
else { usage(); return 1; }
return 0;
}
که نتیجه اینجوریه:
scanf: 0.63 sec
unsynced stream: 0.41
به نظر میاد که کار با scanf خیلی جالب نیست!
همون طور که از زمانهای اندازه گیری شده برای یک فایل متنی بزرگ مشخصه اینه که کار باStream(cin & cout)
خیلی سریعتر از scanf هستش...
Don't Expect Anyone Except Yourself,...