关于c++IO的效率

论坛 期权论坛 脚本     
匿名技术用户   2021-1-5 08:51   32   0

自己写了一段测试程序,比较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++的效率还是很高的。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP