计算Windows Mobile / CE设备上的当前CPU使用率

时间:2014-07-30 16:10:07

标签: c# c++ windows-mobile windows-ce cpu

在核心系统中,没有单个调用可以检索整个系统的CPU使用情况。 从我在网上找到的点样片段我需要计算这个总数%但是我无法理解所涉及的数学,我希望有人可以在这方面提供帮助。

我在C#中写这个并且调整一些函数以获得线程时序。 下面是我到目前为止的代码。对于每个正在运行的线程,我可以使用GetThreadTick和GetThreadTimings获取时序。我只是想不出这些值将如何帮助我计算CPU使用率百分比。

我也知道我做的任何计算都会影响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;
    }

3 个答案:

答案 0 :(得分:1)

您可以使用GetIdleTime或CeGetIdleTimeEx(单核或多核版本)来获取CPU在空闲状态下所花费的时间,并使用此值来计算CPU(或每个核心)的负载百分比。 此功能要求BSP支持空闲计数器,如果BSP中缺少此支持,则不会获得有意义的值。

答案 1 :(得分:0)

在我的cpumon中,我使用GetThreadTick获取用于所有线程的用户和内核时间,并为所有进程构建总和:http://www.hjgode.de/wp/2012/12/14/mobile-development-a-remote-cpu-monitor-and-cpu-usage-analysis/

代码段:

    /// <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");
    }

答案 2 :(得分:0)

MSDN记录了获取整个系统空闲时间的计算。

这是一个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();
}

等效的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;
}

在大多数CE平台上,每秒执行一次此计算的开销几乎可以忽略不计。