Home > Net >  ComputerInfo.TotalPhysicalMemory() displays 17 GB of RAM instead of 16
ComputerInfo.TotalPhysicalMemory() displays 17 GB of RAM instead of 16

Time:12-27

I've been working on some Winforms C# application and thought about adding a functionality that shows you the RAM usage of the process / the total physical RAM in your computer.

I looked for some built-in Microsoft methods that help me with this, and I found out that the total RAM memory in my PC can be returned by using: Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory.
Its documentation states that this property holds the total amount of physical memory of the computer.

More can be read from here: ComputerInfo.TotalPhysicalMemory documentation.

This is how I've implemented it:

ulong ram = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
Console.WriteLine("total: "   ram/1000000000);

ram is in bytes and I wanted the result in GB, so I divided it by 10^9.

I'm confused about the output, though:

total: 17

(...) and am pretty sure that there isn't any mistake made by me (when trying to get this property), neither by Microsoft :) because I know that my PC has a physical memory of 16 GB.

My question would be, why does it display 17? Is it about the fact that RAM manufacturers only approximate the amount of RAM, but it is possible to always have more/less than 16 GB? Or do I miss something?

CodePudding user response:

There are 2 issues:

  1. A GB is not 1000000000 bytes:
    KB is 1024 bytes, MB is 1024 KB, and GB is 1024 MB.
    Therefore a GB is 1024^3 bytes.
  2. In case your system does not have an exact multiple of 1024^3 bytes, you can round to the closest integer value to get the number of GB usually reported for the hardware.

Complete example:

ulong ram = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
const ulong GB_BYTES = 1024 * 1024 * 1024;
ulong ramGB = (ulong)Math.Round((double)ram / GB_BYTES);
Console.WriteLine("total GB: "   ramGB);

Output in your case should be:

16
  • Related