windows下内存分配方式的性能对比

今天写了一个小程序测试了一下在windows系统上不同内存分配方式间的性能差异,比较内容:VirtualAlloc,malloc,new,和HeapAlloc。代码很简单,循环分配并释放内存,最后计算每种方法所耗用的时间。

测试结果:

Virtual Memory total time:125,kernel:125,user:0
new total time:203,kernel:171,user:31
malloc total time:125,kernel:125,user:0
heap total time:125,kernel:109,user:15
Press any key to continue . . .

代码:

#include "stdafx.h"
#include "dlclib.h"
#include
using namespace std;
const int LOOPS = 1000;

void PrintResult(CProfileWatch& watch, LPCSTR pszMethod)
{
cout << pszMethod << "t"
<< "total time:" << watch.GetTotalTimeElapsedMs()
<< ",kernel:" << watch.GetKernelTimeElapsedMs()
<< ",user:" << watch.GetUserTimeElapsedMs()
<< "n";
}
int _tmain(int argc, _TCHAR* argv[])
{
SYSTEM_INFO info;
::GetSystemInfo(&info);
DWORD dwPageSize = info.dwPageSize;
CProfileWatch watch;
DWORD dwSize = MemAlign(1024 * 1024 * 10, dwPageSize);
watch.Start();
for (int i = 0; i < LOOPS; ++i)
{
void* pMem = ::VirtualAlloc(NULL, dwSize, MEM_RESERVE |
MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE);
::VirtualFree(pMem, 0, MEM_RELEASE);
}
watch.Stop();
PrintResult(watch, "Virtual Memory");

watch.Start();
for (int i = 0; i < LOOPS; ++i)
{
void* pMem = new char[dwSize];
delete []pMem;
}
watch.Stop();
PrintResult(watch, "new");

watch.Start();
for (int i = 0; i < LOOPS; ++i)
{
void* pMem = malloc(dwSize);
free(pMem);
}
watch.Stop();
PrintResult(watch, "malloc");
HANDLE hHeap = ::HeapCreate(HEAP_NO_SERIALIZE, 0, 0);
watch.Start();
for (int i = 0; i < LOOPS; ++i)
{
void* pMem = ::HeapAlloc(hHeap, HEAP_NO_SERIALIZE, dwSize);
::HeapFree(hHeap, HEAP_NO_SERIALIZE, pMem);
}
watch.Stop();
PrintResult(watch, "heap");
::HeapDestroy(hHeap);
return 0;

}

Related posts:


2 Comments »

Johar On June 24th, 2009 at 4:30 am (#)

What do u talk about ? can u fix it ?

shuigji On March 25th, 2009 at 8:01 pm (#)

go!http://www.dubozuobi.com


Leave a comment


(will not be published)