성능이 크게 향상되었지만 데이터가 어떻게 사용될 것인지 매우 신중해야합니다. 다중 스레드 인 경우 데이터에 대한 액세스 제어를 제공해야합니다. 내가 잘못 본게 아니라면 이미 초기화 된 정적 변수가 어쨌든 "시스템"에 의해 수행되는 경우
#include <windows.h>
#include <stdio.h>
void StartTime (LARGE_INTEGER * pTime)
{
QueryPerformanceCounter (pTime);
}
ULONG EndTime(LARGE_INTEGER * pTime)
{
LARGE_INTEGER liDiff;
LARGE_INTEGER liFreq;
QueryPerformanceCounter(&liDiff);
liDiff.QuadPart -= pTime->QuadPart;
liDiff.QuadPart *= 1000; // Adjust to milliseconds, shouldn't overflow...
(void)QueryPerformanceFrequency(&liFreq);
return ((ULONG)(liDiff.QuadPart/liFreq.QuadPart));
}
void functionCalledLotsofTimesStatic(int size)
{
static int *localarray = NULL;
//size is a large constant > 10 000
if (localarray == NULL) localarray = new int[size];
//Algorithm goes here
}
void functionCalledLotsofTimesDynamic(int size)
{
int *localarray = NULL;
//size is a large constant > 10 000
if (localarray == NULL) localarray = new int[size];
//Algorithm goes here
delete [] localarray;
}
int _tmain(int argc, _TCHAR* argv[])
{
LARGE_INTEGER liTimeDynamic, liTimeStatic;
StartTime (& liTimeDynamic);
for (int loop = 0; loop < 100000 ; loop++)
{
functionCalledLotsofTimesDynamic (10000);
}
printf ("Time dynamic alocation : %lu milliseconds\n", EndTime(&liTimeDynamic));
StartTime (& liTimeStatic);
for (int loop = 0; loop < 100000 ; loop++)
{
functionCalledLotsofTimesStatic (10000);
}
printf ("Time staic alocation : %lu milliseconds\n", EndTime(&liTimeStatic));
return 0;
}
매개 변수를 만들면 완벽하게 유효한 최적화라고 말할 수 있습니다. – GManNickG
'size'가 상수라면, 여기에'new []'를 사용할 이유가 없으며, 스택에 선언하거나 다른 사람들이 제안한 것처럼 함수에 전달할 이유가 없습니다. – Justicle
@Justicle : 때때로 스택 공간이 문제가 될 수 있습니다. 즉, 나는'std :: vector'가 미가공 포인터보다 더 적절하다고 언급 했어야했다. – GManNickG