如何加快C++读取数据的速度

我们来聊聊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,再一次刷新记录。

  • 8
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值