c++and c read test

本文通过实现C和C++两种语言中的文件读取操作,并使用benchmark进行性能测试,展示了不同语言处理文件I/O的速度差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值