PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

GetThreadTimes code problem

I write the following code and put the SumThreadTimes(); in OnInitDialog().

But it doesn't show value on my edit box(m_cpu), am I making a mistake? Thank for help.

Code:

int CCPU_UsageDlg::SumThreadTimes()
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

int newKernel=0;
int oldKernel=0;
int newUser=0;
int oldUser=0;
int newTime=0;
int oldTime=0;
int CPU_Usage=0;

THREADENTRY32 entry;
entry.dwSize = sizeof(THREADENTRY32);

Thread32First(hSnapShot, &entry;);

FILETIME creation, exit, kernel, user;
do
{
if(GetThreadTimes( (HANDLE) entry.th32ThreadID , &creation;, &exit;, &kernel;, &user;)==0)
{
AfxMessageBox (_T("Can't get thread time!"));
}
else
{
oldKernel=newKernel;
oldUser=newUser;
oldTime=newTime;
newKernel += kernel.dwLowDateTime;
newUser += user.dwLowDateTime;
newTime += creation.dwLowDateTime;

entry.dwSize = sizeof(THREADENTRY32);

CPU_Usage=(newKernel-oldKernel+newUser-oldUser)/(newTime-oldTime);

UpdateData(false);

this->m_cpu=(CString)CPU_Usage;

AfxMessageBox (_T("Success"));
}
Sleep(1000);

} while( Thread32Next(hSnapShot, &entry;) );
CloseToolhelp32Snapshot(hSnapShot);
}

You can't cast an int to a CString. If you do it simply sets the CString to a single character whose UNICODE character value will be that of the int.

Try changing line 40 to this:

Code:

this->m_cpu.Format(_T("%d"), CPU_Usage);


Also, you should call UpdateData(FALSE); after line 40 instead of before it. I assume m_cpu is a CString bound to the value of a control in the CDialog. In that case you would want to call UpdateData(FALSE) after you have made changes to the variable(s), and want all the variables' data to be set to their corresponding controls.

Finally, line 36 will always result in a value of 0. You are using integer math, and the numerator will always be less than the denominator.

This will give you the percentage:

Code:

CPU_Usage=100*(newKernel-oldKernel+newUser-oldUser)/(newTime-oldTime);


Dan East
Thank for your reply.

But it doesn't response at all. Should I do any modification for get CPU load?

The evc4.0 project as attached.
Thank for your help.
Attachments:
temp.jpg
CPU_Usage.zip (149 KB)
Well, my eVC4 install is somehow screwed up. If I open a project that defaults to the PPC 2003 SDK, or try to switch to PPC 2003 SDK via the GUI, eVC4 locks up and maxes out the CPU. I tried uninstalling and reinstalling the PPC 2003 SDK but that didn't help.

Does the "Success" message box appear?

Dan East
Dan East wrote:Well, my eVC4 install is somehow screwed up. If I open a project that defaults to the PPC 2003 SDK, or try to switch to PPC 2003 SDK via the GUI, eVC4 locks up and maxes out the CPU. I tried uninstalling and reinstalling the PPC 2003 SDK but that didn't help.

Does the "Success" message box appear?

Dan East


Sorry, I use EVC4.0 + PPC2003 SDK,and use ARMV4 CPU.

No, it doesn't display the "Success" message box.

Someone give me example, but I don't understand why do it.

Code:

ThreadTimes threadTimes( &hashfcn, HASH_COUNT );

DWORD permissions = GetCurrentPermissions();
SetProcPermissions( 0xffffffff );

// Do a given number of loops. In each loop, wait for a while,
// then get thread times, then calculate the change in each for
// each thread and report that, divided by the total elapsed
// time.
DWORD id = GetCurrentProcessId();
DWORD lasttc;
for ( int i = 0; i < 10; i++ )
{
DEBUGMSG( 1, ( TEXT( "Pass #%d\r\n" ), i ) );

HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
DWORD tc = GetTickCount();

// Check.
if ( hSnapShot == INVALID_HANDLE_VALUE )
break;

// Enumerate the threads.
THREADENTRY32 te;
te.dwSize = sizeof( te );
if ( Thread32First( hSnapShot, &te ) )
{
do
{
// Do nothing if the thread is ours.
if ( te.th32OwnerProcessID != id )
{
HANDLE threadH = (HANDLE)te.th32ThreadID;

// Process the thread.
__int64 creation;
__int64 exit;
__int64 kernel;
__int64 user;
if ( !GetThreadTimes( (HANDLE)threadH,(FILETIME*)&creation, (FILETIME*)&exit,
(FILETIME*)&kernel, (FILETIME*)&user ) )
{
DEBUGMSG(1,(TEXT("Error in GetThreadTimes.Error code = %d\r\n"),
GetLastError() ) );

// Remove the thread entry, if any, from the table.
threadTimes.remove( te.th32ThreadID );
}
else // if ( !GetThreadTimes( (HANDLE)te.th32ThreadID,
{
__int64 totalTime = kernel + user;

// If this is the first loop, put the values in the 'old' entries
// table and do no calcs. If this is not the first loop, do the calcs
// before saving the old values.
if ( i )
{
__int64 oldTotalTime;

// Get old totalTime.
if ( !threadTimes.findValue( te.th32ThreadID, oldTotalTime ) )
{
DEBUGMSG( 1, ( TEXT( "Error in findValue. No previous entry for thread 0x%x\r\n" ),
te.th32ThreadID ) );
}
else
{
// Subtract.
__int64 timeSpent = totalTime - oldTotalTime;

// Calculate percent of processor total time.
__int64 tcSpent = ( tc - lasttc ) * 10000;

int percent = (int)( ( (double)timeSpent / (double)tcSpent ) * 100 );

// Only show threads which are reasonably active
if ( percent )
{
DEBUGMSG( 1, ( TEXT ("Thread 0x%x took %d%% of the time\r\n" ),
te.th32ThreadID, percent ) );
}
}

// Update time by removing key.
threadTimes.remove( te.th32ThreadID );
}

// Store new time in table.
threadTimes.insertKeyAndValue( te.th32ThreadID, totalTime );

} // if ( !GetThreadTimes( (HANDLE)te.th32ThreadID,
}
else // if ( te.th32OwnerProcessID != id )
{
// DEBUGMSG( 1, ( TEXT( "Our thread = 0x%x\r\n" ), id ) );
}
} while ( Thread32Next( hSnapShot, &te ) );
}

CloseToolhelp32Snapshot( hSnapShot );

// Save last tick count.
lasttc = tc;

Sleep( 5000 );
}

SetProcPermissions( permissions );
Have anybody known this solution?

I need help :(
I rewrite my code,but the value just always increase! 8O

Code:

int CCPU_UsageDlg::SumThreadTimes()
{
DWORD permissions = GetCurrentPermissions();
SetProcPermissions( 0xffffffff );

HANDLE hThreads = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
int newKernel =0;
int newUser =0;
if(hThreads)
{
THREADENTRY32 entry;
entry.dwSize = sizeof(THREADENTRY32);
BOOL more = Thread32First(hThreads, &entry;);

FILETIME creation, exit, kernel, user;
while(more)
{

if(GetThreadTimes( (HANDLE) entry.th32ThreadID , &creation;, &exit;, &kernel;, &user;)==0)
{
AfxMessageBox (_T("Can't get thread time!"));
break;
}
else
{
GetThreadTimes( (HANDLE) entry.th32ThreadID , &creation;, &exit;, &kernel;, &user;);
newKernel += kernel.dwLowDateTime;
newUser += user.dwLowDateTime;

double percent = (double)(newKernel + newUser) * 100.0 * 100.0 / 1000000000.0;
this->m_cpu.Format(_T("%lf %%"), percent);
UpdateData(false);

entry.dwSize = sizeof(THREADENTRY32);
more = Thread32Next(hThreads, &entry;);

Sleep(1500);
}

} CloseToolhelp32Snapshot(hThreads);

}

SetProcPermissions( permissions );
}
maybe change line 27 and line 28 to

Code:

newKernel = kernel.dwLowDateTime;
newUser = user.dwLowDateTime;


And line 30 have bug ?

Code:

double percent = (double)(newKernel + newUser) * 100.0 * 100.0 / 1000000000.0;


OMG~ The results also incorrect :?
You're only treating the lower 32-bits of the times (and you're treating them as signed integers when they're unsigned).

Read the documentation on the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/filetime_str.asp">FILETIME </a> structure and fix your code accordingly.
The following code can get value like *correct* . :wink:
When I execute other application, the value become incorrect. The following code is more close to correct cpu load. :)

Can someone help final steps to find correct answer?

Code:

int CCPU_UsageDlg::SumThreadTimes()
{

DWORD permissions = GetCurrentPermissions();
SetProcPermissions( 0xffffffff );

__int64 creation, exit, kernel, user;
__int64 totalTime1 = 0,totalTime2 = 0 ;
__int64 tc1 = GetTickCount();
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
THREADENTRY32 entry;
entry.dwSize = sizeof(entry);

if (Thread32First(hSnapShot, &entry;))
{
do
{
HANDLE threadH = (HANDLE)entry.th32ThreadID;

if (!GetThreadTimes( (HANDLE)threadH,(FILETIME*)&creation;, (FILETIME*)&exit;,(FILETIME*)&kernel;, (FILETIME*)&user; ) )
{
AfxMessageBox (_T("Can't get thread time!"));
}
else
{
totalTime1 += kernel + user;
}

} while( Thread32Next(hSnapShot, &entry;) );
}
CloseToolhelp32Snapshot(hSnapShot);

Sleep(1000);

__int64 tc2 = GetTickCount();
hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
entry.dwSize = sizeof(entry);

if (Thread32First(hSnapShot, &entry;))
{
do
{
HANDLE threadH = (HANDLE)entry.th32ThreadID;

if (!GetThreadTimes( (HANDLE)threadH,(FILETIME*)&creation;, (FILETIME*)&exit;,(FILETIME*)&kernel;, (FILETIME*)&user; ) )
{
AfxMessageBox (_T("Can't get thread time!"));
}
else
{
totalTime2 += kernel + user;
}

} while( Thread32Next(hSnapShot, &entry;) );
}
CloseToolhelp32Snapshot(hSnapShot);

double up = (totalTime2 - totalTime1)*100 ;
double down = (tc2 - tc1)*10000;

double percent = up / down ;

WCHAR sz[128];

::swprintf(sz,_T("%.3f"),percent);

m_cpu = sz;
this->UpdateData(false);


SetProcPermissions( permissions );

}