关于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++的效率还是很高的。

 

 

你可能感兴趣的:(ios,C++,c,IO,api,null)