Link to home
Start Free TrialLog in
Avatar of DBTechnique
DBTechnique

asked on

Strange time consumption in for loop

Hello Experts,
I have encountered a strange situation.
I have added the corresponding code and the TRACE results.
So basically, I have two / three (three in the example but it is the same behavior with only two for loops), and it is making a huge time consumption on certain index.
Usually, it takes 0 milliseconds, but sometimes, it will take 16 ms.
I am working with VC2010 SP1 with Windows 7 and under Debug mode.
Thanks in advance !

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	HMODULE hModule = ::GetModuleHandle(NULL);

	if (hModule != NULL)
	{
		// initialize MFC and print and error on failure
		if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
		{
			// TODO: change error code to suit your needs
			_tprintf(_T("Fatal Error: MFC initialization failed\n"));
			nRetCode = 1;
		}
		else
		{
			for (unsigned int i = 0 ; i < 100 ; i++)
			{
				DWORD dwT1 = GetTickCount();

				for (unsigned int j = 0 ; j < 500 ; j++)
				{
					for (unsigned int k = 0 ; k < 500 ; k++)
					{
						int Position = 0;
						Position++;
					}
				}

				DWORD dwT2 = GetTickCount();
				TRACE(_T("Delai (%d) = %d\r\n"), i, dwT2 - dwT1);
			}
		}
	}
	else
	{
		// TODO: change error code to suit your needs
		_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
		nRetCode = 1;
	}

	return nRetCode;
}

Open in new window


Delai (0) = 0
...
Delai (5) = 0
Delai (6) = 15
Delai (7) = 0
...
Delai (14) = 0
Delai (15) = 16
Delai (16) = 0
...
Delai (28) = 0
Delai (29) = 15
Delai (30) = 0
...
Delai (63) = 0
Delai (64) = 16
Delai (65) = 0
...
Delai (98) = 0
Delai (99) = 16
Avatar of Neil Russell
Neil Russell
Flag of United Kingdom of Great Britain and Northern Ireland image

Well you loop is doing a total of 500 * 500 * 100 iterations. Thats 25000000 times through a LOOP!!
Avatar of DBTechnique
DBTechnique

ASKER

But why doesn't it take the same time for all the iterations of the first loop ?
SOLUTION
Avatar of Neil Russell
Neil Russell
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
To Infinity08 :
Thanks ! Those are really useful information.
To Sara :
I am too curious now to not try it ^^
Thank you.