c# 获取某个进程的CPU使用百分百(类似任务管理器中显示CPU)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 进程监控
{
class Program
{
static void Main(string[] args)
{
Process[] processes = Process.GetProcessesByName("taskmgr");
foreach (Process instance in processes)
{
Console.WriteLine("");
Console.WriteLine("ProcessName:" + instance.ProcessName);
try
{
//Console.WriteLine("提交大小\t" + instance.PagedMemorySize64 / 1024);
Console.WriteLine("工作设置(内存)\t" + instance.WorkingSet64 / 1024);
Console.WriteLine("线程数\t" + instance.Threads.Count);
Console.WriteLine("句柄数\t" + instance.HandleCount);
}
catch { }
}
Process p = processes[1];
//PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
//PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
var objQuery = new ObjectQuery("select * from Win32_Process WHERE ProcessID = " + p.Id);
var moSearcher = new ManagementObjectSearcher(objQuery);
DateTime firstSample = DateTime.MinValue, secondSample = DateTime.MinValue;
double ProcessorUsage;
double msPassed;
ulong u_OldCPU = 0;
while (true)
{
var gets = moSearcher.Get();
foreach (ManagementObject mObj in gets)
{
try
{
if (firstSample == DateTime.MinValue)
{
firstSample = DateTime.Now;
mObj.Get();
u_OldCPU = (ulong)mObj["UserModeTime"] + (ulong)mObj["KernelModeTime"];
}
else
{
secondSample = DateTime.Now;
mObj.Get();
ulong u_newCPU = (ulong)mObj["UserModeTime"] + (ulong)mObj["KernelModeTime"];
msPassed = (secondSample - firstSample).TotalMilliseconds;
ProcessorUsage = (u_newCPU - u_OldCPU) / (msPassed * 100.0 * Environment.ProcessorCount);
u_OldCPU = u_newCPU;
firstSample = secondSample;
Console.WriteLine("ProcessorUsage:" + (int)ProcessorUsage);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
Console.WriteLine(ex.InnerException.Message);
}
}
Thread.Sleep(1000);
}
Console.ReadLine();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)