title: Calculating the current CPU usage on a Windows Mobile/CE device
body: <p>In the core system there is no single call which retrieves the CPU usage for the whole system. 
  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. </p>
  
  <p>Im writing this in C# and pinvoking some functions to get thread timings. 
  Below is the code ive got so far. For each running thread I can get the timings with GetThreadTick and GetThreadTimings. I just cant think how these values will help me calculate the % CPU usage. </p>
  
  <p>Im also aware that any calculation I do will affect the CPU usage itself. </p>
  
  <pre><code>    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;
      }
  </code></pre>