Reputation: 385
I'm a bit rusty on my mathematics so I hope someone can help me. Using the code below I would like to do the following: Depending on the amount of memory installed, I would like to display the percentage of available memory and not how much is left in megabytes.
private void timer1_Tick(object sender, EventArgs e)
{
string memory;
int mem;
memory = GetTotalMemoryInBytes().ToString();
mem = Convert.ToInt32(memory);
mem = mem / 1048576;
progressBar2.Maximum = mem;
progressBar2.Value = mem - (int)(performanceCounter2.NextValue());
label2.Text = "Available Memory: " + (int)(performanceCounter2.NextValue()) + "Mb";
}
//using Microsoft visual dll reference in c#
static ulong GetTotalMemoryInBytes()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
Upvotes: 1
Views: 1043
Reputation: 10313
For most new machines, the total memory in bytes is at least 2GB. This does not fit into an Int32, so you won't work. Since you want to round up, you should use Math.Ceiling.
ulong total = My.Computer.Info.TotalPhysicalMemory;
ulong available = My.Computer.Info.AvailablePhysicalMemory;
int pctAvailable = (int)Math.Ceiling((double)available * 100 / total);
int pctUsed = (int)Math.Ceiling((double)(total - available) * 100 / total);
Upvotes: 0
Reputation: 5773
(Available memory / Total memory) * 100
will be your percentage.
double percent = ((performanceCounter2.NextValue() * 1.0) / mem) * 100;
label2.Text = "Available Memory: " + percent;
Upvotes: 2
Reputation: 85458
To get a percentage, you use: part/total * 100
, eg:
var Info = Microsoft.VisualBasic.Devices.ComputerInfo();
var PercentAvailable = Info.AvailablePhysicalMemory*1.0/Info.TotalPhysicalMemory * 100;
var PercentLeft = 100 - PercentAvailable;
// or alternatively:
var PercentLeft = (1 - Info.AvailablePhysicalMemory*1.0/Info.TotalPhysicalMemory) * 100;
Upvotes: 2
Reputation: 190945
mem / memory
would be the percentage of used memory. To get the available memory percentage, its 1 minus the result of that. But likely need a double
for that.
Upvotes: 0