Скорость выделения памяти
Программа:
Код:
clock_t start , end;
void* P;
#define SIZE 4
start = clock();
for(int i=0;i<10000000;i++) P=new char[SIZE];
end = clock();
cout<<" time[new] = "<<end-start<<endl;
cout<<(int)P<<endl;
start = clock();
for(int i=0;i<10000000;i++) P=malloc(SIZE);
end = clock();
cout<<" time[malloc] = "<<end-start<<endl;
cout<<(int)P<<endl;
start = clock();
for(int i=0;i<10000000;i++) P=GlobalAlloc(GMEM_FIXED,SIZE);
end = clock();
cout<<" time[GlobalAlloc(GMEM_FIXED)] = "<<end-start<<endl;
cout<<(int)P<<endl;
start = clock();
for(int i=0;i<10000000;i++) P=LocalAlloc(GMEM_FIXED,SIZE);
end = clock();
cout<<" time[LocalAlloc(GMEM_FIXED)] = "<<end-start<<endl;
cout<<(int)P<<endl;
void* P;
#define SIZE 4
start = clock();
for(int i=0;i<10000000;i++) P=new char[SIZE];
end = clock();
cout<<" time[new] = "<<end-start<<endl;
cout<<(int)P<<endl;
start = clock();
for(int i=0;i<10000000;i++) P=malloc(SIZE);
end = clock();
cout<<" time[malloc] = "<<end-start<<endl;
cout<<(int)P<<endl;
start = clock();
for(int i=0;i<10000000;i++) P=GlobalAlloc(GMEM_FIXED,SIZE);
end = clock();
cout<<" time[GlobalAlloc(GMEM_FIXED)] = "<<end-start<<endl;
cout<<(int)P<<endl;
start = clock();
for(int i=0;i<10000000;i++) P=LocalAlloc(GMEM_FIXED,SIZE);
end = clock();
cout<<" time[LocalAlloc(GMEM_FIXED)] = "<<end-start<<endl;
cout<<(int)P<<endl;
Результаты:
#define SIZE 4:
time[new] = 2453
time[malloc] = 2297
time[GlobalAlloc(GMEM_FIXED)] = 2000
time[LocalAlloc(GMEM_FIXED)] = 2015
#define SIZE 8:
time[new] = 2610
time[malloc] = 2343
time[GlobalAlloc(GMEM_FIXED)] = 2032
time[LocalAlloc(GMEM_FIXED)] = 1984
#define SIZE 16:
time[new] = 2578
time[malloc] = 2453
time[GlobalAlloc(GMEM_FIXED)] = 2157
time[LocalAlloc(GMEM_FIXED)] = 2093
#define SIZE 32:
time[new] = 2781
time[malloc] = 2610
time[GlobalAlloc(GMEM_FIXED)] = 2375
time[LocalAlloc(GMEM_FIXED)] = 2312
Как мы видим, malloc результативнее new на 10%, а ...Alloc на 20%.
Кто функции выделения памяти лучше использовать?
Цитата: sigmov
Как мы видим, malloc результативнее new на 10%, а ...Alloc на 20%.
Кто функции выделения памяти лучше использовать?
Кто функции выделения памяти лучше использовать?
Вопрос далеко не только в скорости. Например, если говорить о С++, то только new может вызывать конструкторы для объектов. Имхо, не стоит зацикливаться на скорости. А различия в показателях скорости - это, насколько я знаю, оттого что каждый из вышеупомянутых интерфейсов является соответствущего рода враппером над другим интерфейсом (_Alloc() -> malloc() ->new).