【问题标题】:How to get total CPU % and Memory% usage on Ubuntu in using .NET core application如何在使用 .NET 核心应用程序时获得 Ubuntu 上的总 CPU % 和 Memory% 使用率
【发布时间】:2021-01-05 13:28:20
【问题描述】:

即使PerformanceCounter 在 .NET 内核中也受支持,但在 Ubuntu 操作系统上不受支持,所以有没有办法在 .NET 内核中获得系统整体 CPU 和内存使用情况应用程序(就像 Windows 中显示的任务管理器)?

【问题讨论】:

    标签: linux ubuntu .net-core


    【解决方案1】:

    经过一些搜索工作,我通过以下代码完成了(一些代码来自谷歌搜索结果)。仅供参考

      internal static class CpuMemoryMetrics4LinuxUtils
      {
        private const int DigitsInResult = 2;
        private static long totalMemoryInKb;
    
        /// <summary>
        /// Get the system overall CPU usage percentage.
        /// </summary>
        /// <returns>The percentange value with the '%' sign. e.g. if the usage is 30.1234 %,
        /// then it will return 30.12.</returns>
        public static double GetOverallCpuUsagePercentage()
        {
          // refer to https://stackoverflow.com/questions/59465212/net-core-cpu-usage-for-machine
          var startTime = DateTime.UtcNow;
          var startCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds);
    
          System.Threading.Thread.Sleep(500);
    
          var endTime = DateTime.UtcNow;
          var endCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds);
    
          var cpuUsedMs = endCpuUsage - startCpuUsage;
          var totalMsPassed = (endTime - startTime).TotalMilliseconds;
          var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
    
          return Math.Round(cpuUsageTotal * 100, DigitsInResult);
        }
    
        /// <summary>
        /// Get the system overall memory usage percentage.
        /// </summary>
        /// <returns>The percentange value with the '%' sign. e.g. if the usage is 30.1234 %,
        /// then it will return 30.12.</returns>
        public static double GetOccupiedMemoryPercentage()
        {
          var totalMemory = GetTotalMemoryInKb();
          var usedMemory = GetUsedMemoryForAllProcessesInKb();
    
          var percentage = (usedMemory * 100) / totalMemory;
          return Math.Round(percentage, DigitsInResult);
        }
    
        private static double GetUsedMemoryForAllProcessesInKb()
        {
          var totalAllocatedMemoryInBytes = Process.GetProcesses().Sum(a => a.PrivateMemorySize64);
          return totalAllocatedMemoryInBytes / 1024.0;
        }
    
        private static long GetTotalMemoryInKb()
        {
          // only parse the file once
          if (totalMemoryInKb > 0)
          {
            return totalMemoryInKb;
          }
    
          string path = "/proc/meminfo";
          if (!File.Exists(path))
          {
            throw new FileNotFoundException($"File not found: {path}");
          }
    
          using (var reader = new StreamReader(path))
          {
            string line = string.Empty;
            while (!string.IsNullOrWhiteSpace(line = reader.ReadLine()))
            {
              if (line.Contains("MemTotal", StringComparison.OrdinalIgnoreCase))
              {
                // e.g. MemTotal:       16370152 kB
                var parts = line.Split(':');
                var valuePart = parts[1].Trim();
                parts = valuePart.Split(' ');
                var numberString = parts[0].Trim();
    
                var result = long.TryParse(numberString, out totalMemoryInKb);
                return result ? totalMemoryInKb : throw new FileFormatException($"Cannot parse 'MemTotal' value from the file {path}.");
              }
            }
    
            throw new FileFormatException($"Cannot find the 'MemTotal' property from the file {path}.");
          }
        }
      }
    

    【讨论】:

    • 谢谢,内存路径是特定于 Linux 的,所以我不能跨平台使用它,但是处理器路径很酷。
    【解决方案2】:

    您必须依赖提供 CPU 和内存信息的特定于操作系统的实用程序。 从您的应用程序运行命令并读取/解析返回的输出。

    我发现一篇文章看起来与您想要实现的目标一致。 Reading Windows and Linux memory metrics with .NET Core

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多