[英]Calculating the current CPU usage on a Windows Mobile/CE device
In the core system there is no single call which retrieves the CPU usage for the whole system. 在核心系统中,没有单个调用可以检索整个系统的CPU使用率。 From what I can find online with bits and pieces of sample code I need to calculate this total % but I cant get my head around the Math involved and im hoping someone can help on that front.
从网上可以找到的样本代码片段中,我需要计算出这总百分比,但是我无法理解数学,希望有人在这方面有所帮助。
Im writing this in C# and pinvoking some functions to get thread timings. 我用C#编写了此代码,并添加了一些函数来获取线程计时。 Below is the code ive got so far.
下面是到目前为止的代码。 For each running thread I can get the timings with GetThreadTick and GetThreadTimings.
对于每个正在运行的线程,我都可以使用GetThreadTick和GetThreadTimings获得计时。 I just cant think how these values will help me calculate the % CPU usage.
我只是不认为这些值将如何帮助我计算%CPU使用率。
Im also aware that any calculation I do will affect the CPU usage itself. 我还知道,我所做的任何计算都会影响CPU使用率本身。
public static int Calc()
{
int dwCurrentThreadTime1 = 0;
int dwCurrentThreadTime2 = 0;
FILETIME ftCreationTime = new FILETIME();
FILETIME ftExitTime = new FILETIME();
FILETIME ftKernelTime = new FILETIME();
FILETIME ftUserTime = new FILETIME();
PROCESSENTRY pe32 = new PROCESSENTRY();
THREADENTRY32 te32 = new THREADENTRY32();
IntPtr hsnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD, 0);
if (hsnapshot == IntPtr.Zero)
return -1;
pe32.dwSize = (uint)Marshal.SizeOf(pe32);
te32.dwSize = Marshal.SizeOf(te32);
int retval = Process32First(hsnapshot, ref pe32);
while (retval == 1)
{
int retval2 = Thread32First(hsnapshot, ref te32);
while(retval2 == 1)
{
if (te32.th32OwnerProcessID == pe32.th32ProcessID)
{
int dwCurrentTickTime1 = GetTickCount();
GetThreadTimes((IntPtr)te32.th32ThreadID, ref ftCreationTime, ref ftExitTime, ref ftKernelTime, ref ftUserTime);
GetThreadTick(ref ftKernelTime, ref ftUserTime);
}
retval2 = Thread32Next(hsnapshot, ref te32);
}
retval = Process32Next(hsnapshot, ref pe32);
}
CloseToolhelp32Snapshot(hsnapshot);
return dwCurrentThreadTime1;
}
You can use GetIdleTime or CeGetIdleTimeEx (single core or multi-core version) to get the time the CPU has spent in idle state and use this value to calculate the load percentage of the CPU (or each core). 您可以使用GetIdleTime或CeGetIdleTimeEx(单核或多核版本)来获取CPU在空闲状态下所花费的时间,并使用该值来计算CPU(或每个核)的负载百分比。 This function requires that the BSP supports idle counters, if this support is missing in the BSP you will not get meaningful values.
此功能要求BSP支持空闲计数器,如果BSP中缺少此支持,则不会获得有意义的值。
In my cpumon I use GetThreadTick for user and kernel time spent for all threads and build a sum for all processes: http://www.hjgode.de/wp/2012/12/14/mobile-development-a-remote-cpu-monitor-and-cpu-usage-analysis/ 在我的cpumon中,我将GetThreadTick用于所有线程花费的用户和内核时间,并为所有进程建立一个总和: http ://www.hjgode.de/wp/2012/12/14/mobile-development-a-remote-cpu -monitor-和CPU的使用率分析/
code snippet: 代码段:
/// <summary>
/// build thread and process list periodically and fire update event and enqueue results for the socket thread
/// </summary>
void usageThread()
{
try
{
int interval = 3000;
uint start = Process.GetTickCount();
Dictionary<uint, thread> old_thread_List;// = Process.GetThreadList();
string exeFile = Process.exefile;
//read all processes
Dictionary<uint, process> ProcList = Process.getProcessNameList();
DateTime dtCurrent = DateTime.Now;
//######### var declarations
Dictionary<uint, thread> new_ThreadList;
uint duration;
long system_total;
long user_total, kernel_total; //total process spend in user/kernel
long thread_user, thread_kernel; //times the thread spend in user/kernel
DWORD dwProc;
float user_percent;
float kernel_percent;
ProcessStatistics.process_usage usage;
ProcessStatistics.process_statistics stats = null;
string sProcessName = "";
List<thread> processThreadList = new List<thread>();
//extended list
List<threadStatistic> processThreadStatsList = new List<threadStatistic>(); //to store thread stats
while (!bStopMainThread)
{
eventEnableCapture.WaitOne();
old_thread_List = Process.GetThreadList(); //build a list of threads with user and kernel times
System.Threading.Thread.Sleep(interval);
//get a new thread list
new_ThreadList = Process.GetThreadList(); //build another list of threads with user and kernel times, to compare
duration = Process.GetTickCount() - start;
ProcList = Process.getProcessNameList(); //update process list
dtCurrent = DateTime.Now;
system_total = 0;
statisticsTimes.Clear();
//look thru all processes
foreach (KeyValuePair<uint, process> p2 in ProcList)
{
//empty the process's thread list
processThreadList=new List<thread>();
processThreadStatsList = new List<threadStatistic>();
user_total = 0; //hold sum of thread user times for a process
kernel_total = 0; //hold sum of thread kernel times for a process
sProcessName = p2.Value.sName;
//SUM over all threads with that ProcID
dwProc = p2.Value.dwProcID;
foreach (KeyValuePair<uint, thread> kpNew in new_ThreadList)
{
thread_user = 0;
thread_kernel = 0;
//if the thread belongs to the process
if (kpNew.Value.dwOwnerProcID == dwProc)
{
//is there an old thread entry we can use to calc?
thread threadOld;
if (old_thread_List.TryGetValue(kpNew.Value.dwThreadID, out threadOld))
{
thread_user=Process.GetThreadTick(kpNew.Value.thread_times.user) - Process.GetThreadTick(old_thread_List[kpNew.Value.dwThreadID].thread_times.user);
user_total += thread_user;
thread_kernel =Process.GetThreadTick(kpNew.Value.thread_times.kernel) - Process.GetThreadTick(old_thread_List[kpNew.Value.dwThreadID].thread_times.kernel);
kernel_total += thread_kernel;
}
//simple list
thread threadsOfProcess = new thread(kpNew.Value.dwOwnerProcID, kpNew.Value.dwThreadID, kpNew.Value.thread_times);
processThreadList.Add(threadsOfProcess);
//extended list
threadStatistic threadStats =
new threadStatistic(
kpNew.Value.dwOwnerProcID,
kpNew.Value.dwThreadID,
new threadtimes(thread_user, thread_kernel),
duration,
dtCurrent.Ticks);
processThreadStatsList.Add(threadStats);
}//if dwProcID matches
}
//end of sum for process
user_percent = (float)user_total / (float)duration * 100f;
kernel_percent = (float)kernel_total / (float)duration * 100f;
system_total = user_total + kernel_total;
// update the statistics with this process' info
usage = new ProcessStatistics.process_usage(kernel_total, user_total);
// update process statistics
stats = new ProcessStatistics.process_statistics(p2.Value.dwProcID, p2.Value.sName, usage, dtCurrent.Ticks, duration, processThreadStatsList);
//add or update the proc stats
if (exeFile != p2.Value.sName || bIncludeMySelf)
{
statisticsTimes[p2.Value.sName] = stats;
procStatsQueueBytes.Enqueue(stats.ToByte());
}
start = Process.GetTickCount();
}//foreach process
onUpdateHandler(new ProcessStatsEventArgs(statisticsTimes, duration));
procStatsQueueBytes.Enqueue(ByteHelper.endOfTransferBytes);
((AutoResetEvent)eventEnableSend).Set();
}//while true
}
catch (ThreadAbortException ex)
{
System.Diagnostics.Debug.WriteLine("ThreadAbortException: usageThread(): " + ex.Message);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: usageThread(): " + ex.Message);
}
System.Diagnostics.Debug.WriteLine("Thread ENDED");
}
The calculation to obtain the idle time for the whole system is documented on MSDN . 在MSDN上记录了获得整个系统空闲时间的计算。
Here's a C# sample: 这是一个C#示例:
using System;
using System.Runtime.InteropServices;
using System.Threading;
class Program
{
static void Main()
{
for(;;)
{
uint startTick = GetTickCount();
uint startIdle = GetIdleTime();
Thread.Sleep(1000);
uint stopTick = GetTickCount();
uint stopIdle = GetIdleTime();
uint percentIdle = (100 * (stopIdle - startIdle)) / stopTick - startTick);
Console.WriteLine("CPU idle {0}%", percentIdle);
}
}
[DllImport("coredll.dll")]
static extern uint GetTickCount();
[DllImport("coredll.dll")]
static extern uint GetIdleTime();
}
And the equivalent C/C++ implementation: 以及等效的C / C ++实现:
#include "windows.h"
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
for(;;)
{
DWORD startTick = GetTickCount();
DWORD startIdle = GetIdleTime();
Sleep(1000);
DWORD stopTick = GetTickCount();
DWORD stopIdle = GetIdleTime();
DWORD percentIdle = (100 * (stopIdle - startIdle)) / (stopTick - startTick);
_tprintf(L"CPU idle %d%%\r\n", percentIdle);
}
return 0;
}
On most CE platforms, performing this calculation just once every second has an absolutely negligible overhead. 在大多数CE平台上,每秒执行一次此计算的开销绝对可以忽略不计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.