Wednesday 12 May 2010

Realtime CPU calculation for CE debugging

Quite often I've been in the situation where a process or thread has gone rogue and I've been trying to track down why the system has ground to a halt.

One of the things I find most helpful is the SnapShot tools, this allows you to take a snapshot of the system for its current running processes or threads, this can be useful in itself but using the GetThreadTimes API you can then print out any high CPU users, basically creating your own mini-task manager for Windows CE.

Firstly take a snapshot of the system:

HANDLE hSnapshot = CreateToolhelp32Snapshot (TH32CS_SNAPTHREAD, 0);

Secondly call Thread32First/Next on the snapshot to retrieve all the thread information:

THREADENTRY32 te[256]; // up to 256 threads
int used = 0;
te[used].dwSize = sizeof(THREADENTRY32);
if ( Thread32First(hSnapshot,&te[used]) )
{
do
{
..
..

used++;
te[used].dwSize = sizeof(THREADENTRY32);
}
while (Thread32Next(hSnapshot,&te[used]));
}

Finally iterate through the threads getting their thread times, creating times etc:


FILETIME creationTime,exitTime;
FILETIME ktTime[256];
FILETIME utTime[256];
GetThreadTimes ((HANDLE)te[used].th32ThreadID,
&creationTime,
&exitTime,
&ktTime[used],
&utTime[used]);

This can be done in the while loop above, you can also use the results from the snapshot over and over with a sleep(1000), compare the results and print out the top XX threads using CPU to give some realtime feedback on the system usage.

Commonly my applications and kernel development use this method to ensure that the system is using the expected CPU time when being developed.


No comments: