Code:
void TestMyCode(){
char* lpData=new char[4096];
DWORD dwCount,dwWritten,dwTime;
HANDLE hFile;
dwTime=GetTickCount();
for(int a=0;a<1000;a++){
dwCount=0;
hFile=CreateFileA("a.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,0, 0);
if(hFile!=INVALID_HANDLE_VALUE){
for(int i=0;i<10000;i++){
if(dwCount>=4096){
WriteFile(hFile,lpData,dwCount,&dwWritten,0);
dwCount=0;
}
lpData[dwCount]='*';
dwCount++;
}
WriteFile(hFile,lpData,dwCount,&dwWritten,0);
CloseHandle(hFile);
}
}
DisplayNumber(GetTickCount()-dwTime);
delete[] lpData;
}
void TestCRT(){
FILE *f;
DWORD dwTime;
dwTime=GetTickCount();
for(int a=0;a<1000;a++){
f=fopen("a.txt", "w");
for(int i=0;i<10000;i++){
fputc('*',f);
}
fclose(f);
}
DisplayNumber(GetTickCount()-dwTime);
}
CRT spent 1250/1265/1266/1375 ticks and my code spent 453/656/438/453. But actually I cheated a little bit. You see - I allocated the buffer once, CRT code for every time I opened a file and started writing to it. Let's make things more fair:
Code:
void TestMyCode(){
char* lpData;
DWORD dwCount,dwWritten,dwTime;
HANDLE hFile;
dwTime=GetTickCount();
for(int a=0;a<1000;a++){
lpData=(char*)HeapAlloc(GetProcessHeap(),HEAP_NO_SERIALIZE,4096);
dwCount=0;
hFile=CreateFileA("a.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,0, 0);
if(hFile!=INVALID_HANDLE_VALUE){
for(int i=0;i<10000;i++){
if(dwCount>=4096){
WriteFile(hFile,lpData,dwCount,&dwWritten,0);
dwCount=0;
}
lpData[dwCount]='*';
dwCount++;
}
WriteFile(hFile,lpData,dwCount,&dwWritten,0);
CloseHandle(hFile);
}
HeapFree(GetProcessHeap(),HEAP_NO_SERIALIZE,lpData);
}
Di(GetTickCount()-dwTime);
}
void TestCRT(){
FILE *f;
DWORD dwTime;
dwTime=GetTickCount();
for(int a=0;a<1000;a++){
f=fopen("a.txt", "w");
for(int i=0;i<10000;i++){
fputc('*',f);
}
fclose(f);
}
Di(GetTickCount()-dwTime);
}
Results: CRT - 1250/1234/1375/1344 and direct WinAPI - 437/531/453/437. Seems like allocating memory takes absolutely no time at all compared to writing to hard drive.
But it really does matter if CRT code manages to take 2/3 of the execution time even if I have SO slow hard drive.
My suggestion: If you're bored, do fast code.