繁体   English   中英

测量 C# + Mono 中有多少可用内存

[英]Measuring how much memory is available in C# + Mono

我想测量我的C#代码中有多少系统内存可用。 我相信它是这样做的:

PerformanceCounter ramCounter = new PerformanceCounter(
    "Memory"
    , "Available MBytes"
    , true
);
float availbleRam = ramCounter.NextValue();

问题是Mono没有"Memmory"类别。 我遍历了这样的类别列表:

PerformanceCounterCategory[] cats = PerformanceCounterCategory.GetCategories();
string res = "";
foreach (PerformanceCounterCategory c in cats)
{
    res += c.CategoryName + Environment.NewLine;
}
return res;

我发现的最接近的类别是"Mono Memory" ,它没有"Available MBytes"并且在NextValue调用中一直返回 0。 这是单声道返回类别的完整列表:

Processor
Process
Mono Memory
ASP.NET
.NET CLR JIT
.NET CLR Exceptions
.NET CLR Memory
.NET CLR Remoting
.NET CLR Loading
.NET CLR LocksAndThreads
.NET CLR Interop
.NET CLR Security
Mono Threadpool
Network Interface

那么有人知道在C# + Mono + Ubuntu测量可用内存的方法吗?

[更新]

我设法在Ubuntu这样做(使用外部程序free ):

long GetFreeMemorySize()
{
    Regex ram_regex = new Regex(@"[^\s]+\s+\d+\s+(\d+)$");
    ProcessStartInfo ram_psi = new ProcessStartInfo("free");
    ram_psi.RedirectStandardOutput = true;
    ram_psi.RedirectStandardError = true;
    ram_psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    ram_psi.UseShellExecute = false;
    System.Diagnostics.Process free = System.Diagnostics.Process.Start(ram_psi);
    using (System.IO.StreamReader myOutput = free.StandardOutput)
    {
        string output = myOutput.ReadToEnd();
        string[] lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        lines[2] = lines[2].Trim();
        Match match = ram_regex.Match(lines[2]);
        if (match.Success)
        {
            try
            {
                return Convert.ToInt64(match.Groups[1].Value);
            }
            catch (Exception)
            {
                return 0L;
            }
        }
        else
        {
            return 0L;
        }
    }
}

但是这个解决方案的问题在于它只有在Linux系统中运行时才适用于Mono 我想知道是否有人可以为Mono + Windows提出解决方案?

Thread.Sleep(1000);

把它放在你的第一个“NextValue”调用之后(你可以抛出第一个 NextValue 返回值),然后用你的行跟随它:

float availbleRam = ramCounter.NextValue();

性能计数器需要时间来衡量,然后才能返回结果。

确认这在使用 .net 4.5 的 Windows 中有效,不确定使用 Mono 的 Linux。

我意识到这是一个老问题,但我的回答可能会对某人有所帮助。

您需要找出系统上可用的性能类别和计数器。

foreach (var cat in PerformanceCounterCategory.GetCategories())
{
    Console.WriteLine(cat.CategoryName + ":");
    foreach (var co in cat.GetCounters())
    {
        Console.WriteLine(co.CounterName);
    }                
}

然后您将需要使用相应的值来衡量性能。

对于 Windows,这些应该是:

var memory = new PerformanceCounter("Memory", "Available MBytes");

对于 Linux(在 Yogurt 0.2.3 上测试):

var memory = new PerformanceCounter("Mono Memory", "Available Physical Memory");

这些值可能因操作系统而异,但您可以通过迭代每个类别的类别和计数器来找到正确的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM