如何加快C++讀取資料的速度
阿新 • • 發佈:2021-01-18
技術標籤:閒聊
我們來聊聊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,再一次重新整理記錄。