关于c++IO的效率

自己写了一段测试程序,比较c++ IO读和c语言的IO读的效率:

 

 

 

long tickcount = GetTickCount();//取得系统启动后的时间(miliseconds)

    int k = 0;

cout << "For c API   " << endl; 

for (int i = 0; i < 10000; ++i)

{

FILE* f = fopen("c://temp//test.txt", "rb");

if (NULL != f)

{

if (fseek(f, 0, SEEK_END) == 0)

{

int length = ftell(f);

fseek(f, 0, SEEK_SET);

char* p = (char*)malloc(length*sizeof(char) + 1);

if (p != NULL)

{

fread((void*)p, length, 1, f );

p[length] = '/0';

// cout << p << endl;

}

free(p);

}

fclose(f);

k++;

}

}

 

long newtickcount = GetTickCount();

cout << "Repeated times: " << k << endl;

cout << "time costed" << newtickcount - tickcount << endl;

 

    tickcount = GetTickCount();

cout << "for c++ API" << endl ;

int j = 0;

for (int i = 0; i < 10000; ++i)

{

ifstream f;

f.open("c://temp//test.txt", ios_base::in | ios_base::binary | ios_base::ate);

if (f.good())

{

 int size = f.tellg();

 char* p = (char*)malloc(size*sizeof(char) + 1);

 f.seekg(ios_base::beg);

 if (p != NULL)

 {

   f.read(p, size);

   p[size] = '/0';

       free(p);

 }

 f.close();

 j++;

}

}

    newtickcount = GetTickCount();

cout << "Reoeated times  " << j << endl;

cout << "Time costed" << newtickcount - tickcount << endl;

 

 

 

结果显示两者效率相当。可见c++的效率还是很高的。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值