c++ windows 内存分配比较malloc,new,VirtualAlloc,HeapAllpc

转载 ,找不到 转载连接了  win7 64

发现  HeapAlloc 效率最高  堆上分配内存

	/******************************************************************
*
* Copyright (c) 2008, xxxx
* All rights reserved.
*
* 文件名称:main.cpp
* 摘    要: 测试申请内存的速度
*
* 当前版本:1.0
* 作     者:吴会然
* 完成日期:2008-11-30
*
* 取代版本:
* 原   作者:
* 完成日期:
*
******************************************************************/


		int i = 0;
		DWORD dw1 = 0, dw2 = 0, dw3 = 0, dw4 = 0;
		DWORD dwStart = 0;
		DWORD dwEnd = 0;
		for (int j = 0; j < 10; j++)
		{
			dwStart = ::GetTickCount();
			for (i = 0; i < 20000; i++)
			{
				char *pDest1 = (char *)malloc(4096);
				free(pDest1);

			}
			dwEnd = ::GetTickCount();
			cout << "malloc 10000次4096大小的内存块,耗时" << dwEnd - dwStart << endl;
			dw1 += dwEnd - dwStart;

			dwStart = ::GetTickCount();
			for (i = 0; i < 20000; i++)
			{
				char *pDest2 = new char[4096];
				delete pDest2;

			}
			dwEnd = ::GetTickCount();
			cout << "new 10000次4096大小的内存块,耗时" << dwEnd - dwStart << endl;
			dw2 += dwEnd - dwStart;

			dwStart = ::GetTickCount();
			for (i = 0; i < 20000; i++)
			{
				void* pMem = ::VirtualAlloc(NULL, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
				::VirtualFree(pMem, 0, MEM_RELEASE);
			}
			dwEnd = ::GetTickCount();
			cout << "VirtualAlloc 10000次4096大小的内存块,耗时" << dwEnd - dwStart << endl;
			dw3 += dwEnd - dwStart;

			HANDLE hHeap = ::HeapCreate(HEAP_NO_SERIALIZE, 0, 0);
			dwStart = ::GetTickCount();
			for (i = 0; i < 20000; i++)
			{
				void* pMem2 = ::HeapAlloc(hHeap, HEAP_NO_SERIALIZE, 4096);
				::HeapFree(hHeap, HEAP_NO_SERIALIZE, pMem2);

			}
			dwEnd = ::GetTickCount();
			cout << "HeapAlloc 10000次4096大小的内存块,耗时" << dwEnd - dwStart << endl;
			dw4 += dwEnd - dwStart;

		}

		TRACE("malloc:%d\n",dw1 );
		TRACE( "new:%d\n" , dw2 );
		TRACE( "VirtualAlloc:%d\n",dw3 );
		TRACE("HeapAlloc:%d\n",dw4);

猜你喜欢

转载自blog.csdn.net/y281252548/article/details/114278748