我们来聊聊C++有时经常会遇到的瓶颈——读写。参考:https://byvoid.com/zhs/blog/fast-readfile/
首先,利用如下的代码,生成1亿个整数:
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <time.h>
using namespace std;
int main() {
ofstream out("data.txt");
int N = 100000000;
srand((unsigned)time(nullptr));
while (N--) {
int d = rand() % 35000;
out << d << " ";
}
return 0;
}
生成后结果:
这个txt大小约半个G.
用C++ ifstream流读取数据
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <time.h>
using namespace std;
int main() {
ifstream in("data.txt");
int a;
clock_t start = clock();
while (in >> a) {
}
clock_t enend = clock();
cout << (enend-start)/1000.0 << "s";
return 0;
}
运行时间为14.471s
改用C读取数据
#include <stdio.h>
#include <time.h>
int main() {
freopen("data.txt", "r", stdin);
int a;
clock_t start = clock();
while (~scanf("%d",&a)) {
}
clock_t enend = clock();
printf("%.3f",(enend-start)/1000.0);
return 0;
}
运行时间为8.914s
意料之中,C的读取效率还是把C++吊起来打。
C++关闭流同步
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <time.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
ifstream in("data.txt");
int a;
clock_t start = clock();
while (in >> a) {
}
clock_t enend = clock();
cout << (enend-start)/1000.0 << "s";
return 0;
}
运行时间为14.271s,看起来比没关闭流同步快不了多少。
上面是一个数一个数读取,我们尝试读取整个文件,再把里面的数据进行分离,看看会不会更快。
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <time.h>
using namespace std;
char buffer[(int)(1e8)*4+10];
int main() {
freopen("data.txt", "rb", stdin);
clock_t start = clock();
int a = 0;
int len = fread(buffer, 1, (int)(1e8)*4, stdin);
buffer[len] = '\0';
char* ptr = buffer;
while (*ptr != '\0') {
if (*ptr != ' ') {
a = a*10 + (*ptr-'0');
} else {
a = 0;
}
++ptr;
}
clock_t enend = clock();
cout << (enend-start)/1000.0 << "s";
return 0;
}
运行时间为1.119s,再一次刷新记录。