我的数学有点生疏,所以我希望有人可以帮助我。使用下面的代码我想执行以下操作:根据安装的内存量,我想显示可用内存的百分比,而不是以兆字节为单位剩余的内存。
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;
}
答案 0 :(得分:2)
要获得百分比,请使用:part/total * 100
,例如:
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;
答案 1 :(得分:2)
(Available memory / Total memory) * 100
将是您的百分比。
double percent = ((performanceCounter2.NextValue() * 1.0) / mem) * 100;
label2.Text = "Available Memory: " + percent;
答案 2 :(得分:0)
mem / memory
将是已用内存的百分比。要获得可用的内存百分比,其1减去其结果。但可能需要double
。
答案 3 :(得分:0)
对于大多数新机器,总内存(以字节为单位)至少为2GB。这不适合Int32,所以你不会工作。由于你想要四舍五入,你应该使用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);