Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get used memory in %

I've created a performancecounter that can check the total memory usage in %, but the problem is that it doesn't give me the same value as in task manager shows me. for example: my program says 34% but task manager says 40%.

Any ideas?

NOTE
I try to get the available RAM of the system, not the used RAM by a process.

Current Code

private PerformanceCounter performanceCounterRAM = new PerformanceCounter();  performanceCounterRAM.CounterName = "% Committed Bytes In Use"; performanceCounterRAM.CategoryName = "Memory";  progressBarRAM.Value = (int)(performanceCounterRAM.NextValue());             labelRAM.Text = "RAM: " + progressBarRAM.Value.ToString(CultureInfo.InvariantCulture) + "%"; 

EDIT
I refresh the progressbar and the label every second with a timer.

like image 281
Yuki Kutsuya Avatar asked Apr 05 '12 11:04

Yuki Kutsuya


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.


2 Answers

You could use GetPerformanceInfo windows API, it shows exactly the same values as Windows Task Manager on Windows 7, here is the console application that get's available physical memory, you could easily get other information that GetPerformanceInfo returns, consult MSDN PERFORMANCE_INFORMATION structure documentation to see how to calculate value in MiB, basically all SIZE_T values are in pages, so you must multiply it with PageSize.

Update: I updated this code to show percentage, it's not optimal because it's calling GetPerformanceInfo two times, but I hope that you get the idea.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices;  namespace ConsoleApplicationPlayground {   class Program   {     static void Main(string[] args)     {       while (true)       {         Int64 phav = PerformanceInfo.GetPhysicalAvailableMemoryInMiB();         Int64 tot = PerformanceInfo.GetTotalMemoryInMiB();         decimal percentFree = ((decimal)phav / (decimal)tot) * 100;         decimal percentOccupied = 100 - percentFree;         Console.WriteLine("Available Physical Memory (MiB) " + phav.ToString());         Console.WriteLine("Total Memory (MiB) " + tot.ToString());         Console.WriteLine("Free (%) " + percentFree.ToString());         Console.WriteLine("Occupied (%) " + percentOccupied.ToString());         Console.ReadLine();       }     }   }    public static class PerformanceInfo   {     [DllImport("psapi.dll", SetLastError = true)]     [return: MarshalAs(UnmanagedType.Bool)]     public static extern bool GetPerformanceInfo([Out] out PerformanceInformation PerformanceInformation, [In] int Size);      [StructLayout(LayoutKind.Sequential)]     public struct PerformanceInformation     {       public int Size;       public IntPtr CommitTotal;       public IntPtr CommitLimit;       public IntPtr CommitPeak;       public IntPtr PhysicalTotal;       public IntPtr PhysicalAvailable;       public IntPtr SystemCache;       public IntPtr KernelTotal;       public IntPtr KernelPaged;       public IntPtr KernelNonPaged;       public IntPtr PageSize;       public int HandlesCount;       public int ProcessCount;       public int ThreadCount;     }      public static Int64 GetPhysicalAvailableMemoryInMiB()     {         PerformanceInformation pi = new PerformanceInformation();         if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))         {           return Convert.ToInt64((pi.PhysicalAvailable.ToInt64() * pi.PageSize.ToInt64() / 1048576));         }         else         {           return -1;         }      }      public static Int64 GetTotalMemoryInMiB()     {       PerformanceInformation pi = new PerformanceInformation();       if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))       {         return Convert.ToInt64((pi.PhysicalTotal.ToInt64() * pi.PageSize.ToInt64() / 1048576));       }       else       {         return -1;       }      }   } } 
like image 61
Antonio Bakula Avatar answered Oct 19 '22 12:10

Antonio Bakula


Performance counters is not good idea. Use this code to get % of memory usage from Task Manager

var wmiObject = new ManagementObjectSearcher("select * from Win32_OperatingSystem");  var memoryValues = wmiObject.Get().Cast<ManagementObject>().Select(mo => new {     FreePhysicalMemory = Double.Parse(mo["FreePhysicalMemory"].ToString()),     TotalVisibleMemorySize = Double.Parse(mo["TotalVisibleMemorySize"].ToString()) }).FirstOrDefault();  if (memoryValues != null) {     var percent = ((memoryValues.TotalVisibleMemorySize - memoryValues.FreePhysicalMemory) / memoryValues.TotalVisibleMemorySize) * 100; } 
like image 22
ZOXEXIVO Avatar answered Oct 19 '22 11:10

ZOXEXIVO