none
C# memory usage for a process and compare to Windows Task Manager

    Question

  • hello,

    i'm working to add a function to my  existing program which will allow me to take a snapshot of all the running processes and report the memory and CPU usages.

    i have read a lot about which method to use but i'm not clear on why i can't match what is seen in the task manager.

    from what i have read Windows Task Manager samples at one rate and while my snapshot will be immediate.

    my question is how do i know which is right, Task Manager or my snapshot?

    also i'm not clear which method it the best:

    PrivateMemorySize
        The number of bytes that the associated process has allocated that cannot be shared with other processes.
    PeakVirtualMemorySize
        The maximum amount of virtual memory that the process has requested.
    PeakPagedMemorySize
        The maximum amount of memory that the associated process has allocated that could be written to the virtual paging file.
    PagedSystemMemorySize
        The amount of memory that the system has allocated on behalf of the associated process that can be written to the virtual memory paging file.
    PagedMemorySize
        The amount of memory that the associated process has allocated that can be written to the virtual memory paging file.
    NonpagedSystemMemorySize
        The amount of memory that the system has allocated on behalf of the associated process that cannot be written to the virtual memory paging file.

    like i said none seem close to what Task manager shows.

    any help would be appreciated.

    Friday, June 03, 2011 12:05 AM

Answers

  • There are various memory usage items, please check this Memory Performance Information.
     static void Main(string[] args)
     {
      getallmemoryusage();
      Console.ReadLine();
     }
    
     private static void getallmemoryusage()
     {
      /*
      PrivateMemorySize
      The number of bytes that the associated process has allocated that cannot be shared with other processes.
      PeakVirtualMemorySize
      The maximum amount of virtual memory that the process has requested.
      PeakPagedMemorySize
      The maximum amount of memory that the associated process has allocated that could be written to the virtual paging file.
      PagedSystemMemorySize
      The amount of memory that the system has allocated on behalf of the associated process that can be written to the virtual memory paging file.
      PagedMemorySize
      The amount of memory that the associated process has allocated that can be written to the virtual memory paging file.
      NonpagedSystemMemorySize
      The amount of memory that the system has allocated on behalf of the associated process that cannot be written to the virtual memory paging file.
      */
      double f = 1024.0;
      Process[] localByName = Process.GetProcessesByName("360Safe");
      foreach (Process p in localByName)
      {
      Console.WriteLine("Private memory size64: {0}", (p.PrivateMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Working Set size64: {0}", (p.WorkingSet64/f).ToString("#,##0"));
      Console.WriteLine("Peak virtual memory size64: {0}", (p.PeakVirtualMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Peak paged memory size64: {0}", (p.PeakPagedMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Paged system memory size64: {0}", (p.PagedSystemMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Paged memory size64: {0}", (p.PagedMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Nonpaged system memory size64: {0}", (p.NonpagedSystemMemorySize64 / f).ToString("#,##0"));
      }
     }
    

    In the task manager, there are more than one column to incidate the memory usage:



    While the memory items in the task manager are restricted/not enough. You can use the Process Explorer to check all items of memory usage:



    Actually the data get by the Performance Monitor is the most accurate:

    Leo Liu [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.



    Wednesday, June 08, 2011 6:57 AM
    Moderator
  • The data matches, merely that some tiny disparity exists.
    The correspondences are as below:

    Task Manager                               Performance Monitor
    ---------------------------------        -----------------------
    Memory(Private Working Set) -->  Working Set-Private
    Working Set(Memory)            -->  Working Set
    Peak Working Set(Memory)    -->  Working Set Peak
    ...

    Beside these tools, if you want to monitor the usage of the memory or CPU through programming, your code snippet is OK as well as using WMI.


    Leo Liu [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by hauld Friday, June 10, 2011 3:11 PM
    Thursday, June 09, 2011 2:13 AM
    Moderator

All replies

  • You can try Microsoft Spy++ (part of VS tool set) to get the complete map of the currently running Windows, Processes, Threads.
    Friday, June 03, 2011 2:43 AM
  • >> i'm not clear on why i can't match what is seen in the task manager.
    Do you mean that the list of the running processes got with one method you used do not match the list saw from the Task Manager?
    If so please make sure you've checked the "Show processes from all users" in the Processes tab of the Task Manager window.

    I think WMI is a good choice for you, its syntax is simple.
    You can have a look at the following demo project. I've tested with it, the running processes list is just the same with the one got from the Task Manager.
    http://www.codeproject.com/KB/system/wmi.aspx.
    Leo Liu [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, June 03, 2011 8:00 AM
    Moderator
  • You can use the PerformanceMonitor Class in base class libararies to get detailed information of processes and things realted to memory usage like private memory usage.

    Hope it helps.


    Abhinav Galodha
    Friday, June 03, 2011 8:16 AM
  • thank you all for your response.

    i don't want to use Microsoft spy++ because i need to add this function to my existing C# program.

    i meant to say that my attempt to display the memory usages (i'm only testing one service for now to make sure i know how) does not match what Task Manager shows in its "memory usage".

    i'm not clear what Task Manager uses for its "memory usage" from the list i mention above. i tried them all and they don't match, there are large deltas.

    Friday, June 03, 2011 1:33 PM
  • Could you provide your code for us to march on?
    Thanks.


    Leo Liu [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, June 07, 2011 2:14 AM
    Moderator
  • i have been playing around with different things hoping to if the correct combination that will get me close.

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.Management;
    using System.Threading;
    
    namespace Display_memoryUsage
    {
      class Program
      {
        static void Main(string[] args)
        {
          testprocess();
          GetProcessorIdleTime("HAF");
          getPageMemory();
          getallmemoryusage();
          
          Console.ReadLine();
        }
    
        private static void getPageMemory()
        {
          Process[] localByName = Process.GetProcessesByName("itunes");
          foreach (Process p in localByName)
          {
            string memoryUse = (p.PagedMemorySize64 / 1024).ToString("#,##0");
            Console.WriteLine("Memory usage: {0}", memoryUse);
          }
        }
    
        private static void GetProcessorIdleTime(string selectedServer)
        {
          Int32 iReturn = 0;
    
          try
          {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + selectedServer + "\\root\\CIMV2", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");
            ManagementObjectCollection collection = searcher.Get();
            ManagementObject queryObj = collection.Cast<ManagementObject>().First();
            iReturn = Convert.ToInt32(queryObj["PercentIdleTime"]);
          }
          catch (ManagementException e)
          {
            Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
          }
    
          Console.WriteLine("Idle CPU: {0}", iReturn.ToString("#,##0"));
    
        }
    
        private static void testprocess()
        {
          PerformanceCounter myAppCpu = new PerformanceCounter("Process", "% Processor Time", "itunes", true);
          Console.WriteLine("Press the any key to stop...\n");
          while (!Console.KeyAvailable)
          {
            double pct = myAppCpu.NextValue();
            Console.WriteLine("iTunes'S CPU % = " + pct);
            Thread.Sleep(250);
          }
        }
    
        private static void getallmemoryusage()
        {
          /*
            PrivateMemorySize
              The number of bytes that the associated process has allocated that cannot be shared with other processes.
            PeakVirtualMemorySize
              The maximum amount of virtual memory that the process has requested.
            PeakPagedMemorySize
              The maximum amount of memory that the associated process has allocated that could be written to the virtual paging file.
            PagedSystemMemorySize
              The amount of memory that the system has allocated on behalf of the associated process that can be written to the virtual memory paging file.
            PagedMemorySize
              The amount of memory that the associated process has allocated that can be written to the virtual memory paging file.
            NonpagedSystemMemorySize
              The amount of memory that the system has allocated on behalf of the associated process that cannot be written to the virtual memory paging file.
          */
          
          Process[] localByName = Process.GetProcessesByName("itunes");
          foreach (Process p in localByName)
          {
            //string memoryUse = (p.PagedMemorySize64 / 1024).ToString();
            Console.WriteLine("Private memory size64: {0}", (p.PrivateMemorySize64).ToString("#,##0"));
            Console.WriteLine("Peak virtual memory size64: {0}", (p.PeakVirtualMemorySize64).ToString("#,##0"));
            Console.WriteLine("Peak paged memory size64: {0}", (p.PeakPagedMemorySize64).ToString("#,##0"));
            Console.WriteLine("Paged system memory size64: {0}", (p.PagedSystemMemorySize64).ToString("#,##0"));
            Console.WriteLine("Paged memory size64: {0}", (p.PagedMemorySize64).ToString("#,##0"));
            Console.WriteLine("Nonpaged system memory size64: {0}", (p.NonpagedSystemMemorySize64).ToString("#,##0"));
          }
        }
    
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      }//class Program
    }
    

    Tuesday, June 07, 2011 7:17 PM
  • There are various memory usage items, please check this Memory Performance Information.
     static void Main(string[] args)
     {
      getallmemoryusage();
      Console.ReadLine();
     }
    
     private static void getallmemoryusage()
     {
      /*
      PrivateMemorySize
      The number of bytes that the associated process has allocated that cannot be shared with other processes.
      PeakVirtualMemorySize
      The maximum amount of virtual memory that the process has requested.
      PeakPagedMemorySize
      The maximum amount of memory that the associated process has allocated that could be written to the virtual paging file.
      PagedSystemMemorySize
      The amount of memory that the system has allocated on behalf of the associated process that can be written to the virtual memory paging file.
      PagedMemorySize
      The amount of memory that the associated process has allocated that can be written to the virtual memory paging file.
      NonpagedSystemMemorySize
      The amount of memory that the system has allocated on behalf of the associated process that cannot be written to the virtual memory paging file.
      */
      double f = 1024.0;
      Process[] localByName = Process.GetProcessesByName("360Safe");
      foreach (Process p in localByName)
      {
      Console.WriteLine("Private memory size64: {0}", (p.PrivateMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Working Set size64: {0}", (p.WorkingSet64/f).ToString("#,##0"));
      Console.WriteLine("Peak virtual memory size64: {0}", (p.PeakVirtualMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Peak paged memory size64: {0}", (p.PeakPagedMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Paged system memory size64: {0}", (p.PagedSystemMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Paged memory size64: {0}", (p.PagedMemorySize64 / f).ToString("#,##0"));
      Console.WriteLine("Nonpaged system memory size64: {0}", (p.NonpagedSystemMemorySize64 / f).ToString("#,##0"));
      }
     }
    

    In the task manager, there are more than one column to incidate the memory usage:



    While the memory items in the task manager are restricted/not enough. You can use the Process Explorer to check all items of memory usage:



    Actually the data get by the Performance Monitor is the most accurate:

    Leo Liu [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.



    Wednesday, June 08, 2011 6:57 AM
    Moderator
  • still taken back that can't match what Task Manager shows.

    i see that "performance monitor" shows the same data that Task Manager does under the column "private (kb)".

    Wednesday, June 08, 2011 6:23 PM
  • The data matches, merely that some tiny disparity exists.
    The correspondences are as below:

    Task Manager                               Performance Monitor
    ---------------------------------        -----------------------
    Memory(Private Working Set) -->  Working Set-Private
    Working Set(Memory)            -->  Working Set
    Peak Working Set(Memory)    -->  Working Set Peak
    ...

    Beside these tools, if you want to monitor the usage of the memory or CPU through programming, your code snippet is OK as well as using WMI.


    Leo Liu [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by hauld Friday, June 10, 2011 3:11 PM
    Thursday, June 09, 2011 2:13 AM
    Moderator
  • Okay, you want to get the EXACT value, what TaskManager shows?

    System.Diagnostics.Process proc = assign your process here :-)

    int memsize = 0; // memsize in Megabyte
    PerformanceCounter PC = new PerformanceCounter();
    PC.CategoryName = "Process";
    PC.CounterName = "Working Set - Private";
    PC.InstanceName = proc.ProcessName;
    memsize = Convert.ToInt32(PC.NextValue()) / (int)(1024 * 1024);
    PC.Close();
    PC.Dispose();

    Tuesday, January 29, 2013 3:02 PM