查询Windows系统、进程的CPU使用率、内存使用率
using System.Diagnostics; using System.Runtime.Versioning; namespace ConsoleApp1 { class Program { [SupportedOSPlatform("windows")] static void Main(string[] args) { Performance performance = new Performance(); //Sleep的时间间隔 int interval = 10000; while (true) { Console.WriteLine(performance.ProcessPerformance("ConsoleApp1")); Console.WriteLine(performance.SystemPerformance()); Console.WriteLine(); Thread.Sleep(interval); } Console.ReadLine(); } } public class Performance { bool isWindows = OperatingSystem.IsWindows(); [SupportedOSPlatform("windows")] PerformanceCounter totalCpu = new PerformanceCounter("Processor", "% Processor Time", "_Total"); [SupportedOSPlatform("windows")] PerformanceCounter totalMemory = new PerformanceCounter("Process", "Working Set", "_Total"); /// <summary> /// 进程Cpu使用率、内存使用率 /// </summary> /// <param name="processName"></param> /// <returns></returns> [SupportedOSPlatform("windows")] public PerformanceInfo ProcessPerformance(string processName) { PerformanceInfo performanceInfo = new PerformanceInfo(); PerformanceCounter curMemory = new PerformanceCounter("Process", "Working Set", processName); PerformanceCounter curCpu = new PerformanceCounter("Process", "% Processor Time", processName); performanceInfo.CpuUsage = Math.Round(curCpu.NextValue() / Environment.ProcessorCount, 2); performanceInfo.MemoryUsage = Math.Round(curMemory.NextValue() / 1024, 2); return performanceInfo; } /// <summary> /// 系统cpu使用率 /// </summary> /// <returns></returns> [SupportedOSPlatform("windows")] public PerformanceInfo SystemPerformance() { PerformanceInfo performanceInfo = new PerformanceInfo(); if (isWindows) { performanceInfo.CpuUsage = Math.Round(totalCpu.NextValue(), 2); performanceInfo.MemoryUsage = Math.Round(totalMemory.NextValue() / 1024, 2); } return performanceInfo; } } /// <summary> /// 硬件资源使用率 /// </summary> public class PerformanceInfo { /// <summary> /// CPU使用率 /// </summary> public double CpuUsage { get; set; } /// <summary> /// 内存使用率,单位:KB /// </summary> public double MemoryUsage { get; set; } /// <summary> /// 磁盘空间使用率 /// </summary> public double DiskUsage { get; set; } public override string ToString() { return $"CPU使用率:{CpuUsage}%\t内存使用率:{MemoryUsage},空间使用率:{DiskUsage}"; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2020-06-08 拿到钥匙别急着装修!奉上9大建材品牌清单大全,照着买不出错
2013-06-08 2012年福州中小学最新排名