怎样设置C#应用程序cpu占用率高占用CPU的个数

大数据观察专注于大数据方向,分享最具价值的大数据资讯,大数据应用;
同时整合大数据管理技术——云技术及其资讯与应用,提供电子商务、互联网金融,
工商等众多领域的经典案例助力广大用户攻坚大数据难题。
合作邮箱:
备案号:皖ICP备
版权所有,保留一切权利!
weixin-ext欢迎加入我们,一同切磋技术。 &
用户名: &&&
密 码: &
共有 2057 人关注过本帖
标题:C#如何获取某个进程的CPU占用、内存使用及句柄数的?
等 级:新手上路
帖 子:37
结帖率:54.55%
&&问题点数:0&&回复次数:3&&&
C#如何获取某个进程的CPU占用、内存使用及句柄数的?
我想写一个工具用来获取进程某个时刻占用的CPU数,内存数和句柄数,网上找了好久,都未找到能实现的方法,
所以求助一下各位,希望能得到解答。多谢了。
搜索更多相关主题的帖子:
等 级:新手上路
帖 子:37
等 级:贵宾
威 望:13
帖 子:189
专家分:1090
大概是因为不给点数吧,呵呵!
为提高中华编程水平而奋斗
等 级:新手上路
帖 子:37
好吧,我错了
版权所有,并保留所有权利。
Powered by , Processed in 0.032313 second(s), 8 queries.
Copyright&, BCCN.NET, All Rights Reserved8989人阅读
首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程对象。当有了进程对象后,可以通过进程对象名称来创建PerformanceCounter类型对象,通过设定PerformanceCounter构造函数的参数实现获取特定进程的CPU和内存使用情况。
具体实例代码如下:
首先是获取本机中所有进程对象,分别输出某一时刻各个进程的内存使用情况:
2 using System.Collections.G
3 using System.L
4 using System.T
5 using System.D
6 using System.T
8 namespace CSharpPerformance
9 {//该程序可以实时监控所有进程或者指定进程的工作集、私有工作集
class Program
static void Main(string[] args)
//新建一个Stopwatch变量用来统计程序运行时间
Stopwatch watch = Stopwatch.StartNew();
//获取本机运行的所有进程ID和进程名,并输出哥进程所使用的工作集和私有工作集
foreach (Process ps in Process.GetProcesses())
PerformanceCounter pf1 = new PerformanceCounter(&Process&, &Working Set - Private&, ps.ProcessName);
PerformanceCounter pf2 = new PerformanceCounter(&Process&, &Working Set&, ps.ProcessName);
Console.WriteLine(&{0}:{1}
{2:N}KB&, ps.ProcessName, &工作集(进程类)&, ps.WorkingSet64 / 1024);
Console.WriteLine(&{0}:{1}
{2:N}KB&, ps.ProcessName, &工作集
&, pf2.NextValue() / 1024);
//私有工作集
Console.WriteLine(&{0}:{1}
{2:N}KB&, ps.ProcessName, &私有工作集
&, pf1.NextValue() / 1024);
watch.Stop();
Console.WriteLine(watch.Elapsed);
Console.ReadLine();
其中,工作集ps.WorkingSet64是静态的,pf2.NextValue()是动态变化的,工作集包含进程运行时其独占的内存和与其他进程共享的内存的和,而私有工作集是只包含进程独占的内存。
下面一组代码可以动态显示本程序所对应的进程的CPU和内存使用率的变化:
首先是SystemInfo.cs类:
2 using System.Collections.G
3 using System.D
4 using System.T
5 using System.IO;
6 using System.T
7 using System.M
8 using System.Runtime.InteropS
10 namespace CSharpPerformance
public class SystemInfo
private int m_ProcessorCount = 0;
private PerformanceCounter pcCpuL
//CPU计数器
private long m_PhysicalMemory = 0;
//物理内存
private const int GW_HWNDFIRST = 0;
private const int GW_HWNDNEXT = 2;
private const int GWL_STYLE = (-16);
private const int WS_VISIBLE = ;
private const int WS_BORDER = 8388608;
#region AIP声明
[DllImport(&IpHlpApi.dll&)]
extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
[DllImport(&User32&)]
private extern static int GetWindow(int hWnd, int wCmd);
[DllImport(&User32&)]
private extern static int GetWindowLongA(int hWnd, int wIndx);
[DllImport(&user32.dll&)]
private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
[DllImport(&user32&, CharSet = CharSet.Auto)]
private extern static int GetWindowTextLength(IntPtr hWnd);
#endregion
#region 构造函数
/// &summary&
/// 构造函数,初始化计数器等
/// &/summary&
public SystemInfo()
//初始化CPU计数器
pcCpuLoad = new PerformanceCounter(&Processor&, &% Processor Time&, &_Total&);
pcCpuLoad.MachineName = &.&;
pcCpuLoad.NextValue();
m_ProcessorCount = Environment.ProcessorC
//获得物理内存
ManagementClass mc = new ManagementClass(&Win32_ComputerSystem&);
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
if (mo[&TotalPhysicalMemory&] != null)
m_PhysicalMemory = long.Parse(mo[&TotalPhysicalMemory&].ToString());
#endregion
#region CPU个数
/// &summary&
/// 获取CPU个数
/// &/summary&
public int ProcessorCount
return m_ProcessorC
#endregion
#region CPU占用率
/// &summary&
/// 获取CPU占用率
/// &/summary&
public float CpuLoad
return pcCpuLoad.NextValue();
#endregion
#region 可用内存
/// &summary&
/// 获取可用内存
/// &/summary&
public long MemoryAvailable
long availablebytes = 0;
//ManagementObjectSearcher mos = new ManagementObjectSearcher(&SELECT * FROM Win32_PerfRawData_PerfOS_Memory&);
//foreach (ManagementObject mo in mos.Get())
availablebytes = long.Parse(mo[&Availablebytes&].ToString());
ManagementClass mos = new ManagementClass(&Win32_OperatingSystem&);
foreach (ManagementObject mo in mos.GetInstances())
if (mo[&FreePhysicalMemory&] != null)
availablebytes = 1024 * long.Parse(mo[&FreePhysicalMemory&].ToString());
#endregion
#region 物理内存
/// &summary&
/// 获取物理内存
/// &/summary&
public long PhysicalMemory
return m_PhysicalM
#endregion
#region 结束指定进程
/// &summary&
/// 结束指定进程
/// &/summary&
/// &param name=&pid&&进程的 Process ID&/param&
public static void EndProcess(int pid)
Process process = Process.GetProcessById(pid);
process.Kill();
#endregion
#region 查找所有应用程序标题
/// &summary&
/// 查找所有应用程序标题
/// &/summary&
/// &returns&应用程序标题范型&/returns&
public static List&string& FindAllApps(int Handle)
List&string& Apps = new List&string&();
hwCurr = GetWindow(Handle, GW_HWNDFIRST);
while (hwCurr & 0)
int IsTask = (WS_VISIBLE | WS_BORDER);
int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE);
bool TaskWindow = ((lngStyle & IsTask) == IsTask);
if (TaskWindow)
int length = GetWindowTextLength(new IntPtr(hwCurr));
StringBuilder sb = new StringBuilder(2 * length + 1);
GetWindowText(hwCurr, sb, sb.Capacity);
string strTitle = sb.ToString();
if (!string.IsNullOrEmpty(strTitle))
Apps.Add(strTitle);
hwCurr = GetWindow(hwCurr, GW_HWNDNEXT);
#endregion
然后是执行代码:
2 using System.Collections.G
3 using System.L
4 using System.T
5 using System.D
6 using System.T
8 namespace CSharpPerformance
9 {//该程序可以实时监控程序本身对应进程的工作集、私有工作集和CPU使用率
class Program
static void Main(string[] args)
//获取当前进程对象
Process cur = Process.GetCurrentProcess();
PerformanceCounter curpcp = new PerformanceCounter(&Process&, &Working Set - Private&, cur.ProcessName);
PerformanceCounter curpc = new PerformanceCounter(&Process&, &Working Set&, cur.ProcessName);
PerformanceCounter curtime = new PerformanceCounter(&Process&, &% Processor Time&, cur.ProcessName);
//上次记录CPU的时间
TimeSpan prevCpuTime = TimeSpan.Z
//Sleep的时间间隔
int interval = 1000;
PerformanceCounter totalcpu = new PerformanceCounter(&Processor&, &% Processor Time&, &_Total&);
SystemInfo sys = new SystemInfo();
const int KB_DIV = 1024;
const int MB_DIV = 1024 * 1024;
const int GB_DIV = 1024 * 1024 * 1024;
while (true)
//第一种方法计算CPU使用率
//当前时间
TimeSpan curCpuTime = cur.TotalProcessorT
double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
prevCpuTime = curCpuT
Console.WriteLine(&{0}:{1}
{2:N}KB CPU使用率:{3}&, cur.ProcessName, &工作集(进程类)&, cur.WorkingSet64 / 1024,value);//这个工作集只是在一开始初始化,后期不变
Console.WriteLine(&{0}:{1}
{2:N}KB CPU使用率:{3}&, cur.ProcessName, &工作集
&, curpc.NextValue() / 1024,value);//这个工作集是动态更新的
//第二种计算CPU使用率的方法
Console.WriteLine(&{0}:{1}
{2:N}KB CPU使用率:{3}%&, cur.ProcessName, &私有工作集
&, curpcp.NextValue() / 1024,curtime.NextValue()/Environment.ProcessorCount);
//Thread.Sleep(interval);
//第一种方法获取系统CPU使用情况
Console.Write(&\r系统CPU使用率:{0}%&, totalcpu.NextValue());
//Thread.Sleep(interval);
//第二章方法获取系统CPU和内存使用情况
Console.Write(&\r系统CPU使用率:{0}%,系统内存使用大小:{1}MB({2}GB)&, sys.CpuLoad, (sys.PhysicalMemory - sys.MemoryAvailable) / MB_DIV, (sys.PhysicalMemory - sys.MemoryAvailable) / (double)GB_DIV);
Thread.Sleep(interval);
Console.ReadLine();
以上程序可以正常运行,没隔1S刷新一次,实现动态显示本程序对应进程的CPU和内存使用情况。
1. 进程的CPU用户时间和内核时间
使用Process类的UserProcessorTime和PrivilegedProcessorTime属性可以返回当前进程所耗费CPU的用户和内核时间。Process.TotalProcessorTime则代表两者之和。它们都返回TimeSpan结构体对象。
使用这三个属性,可以做一个简单的程序进行进程的CPU时间监控。
如下:(当然在CPU不是很慢的情况下,进行某个操作后不会看到明显的CPU时间增加)
2. 全部CPU的使用统计
统计全部CPU的使用状况,最简单的方法就是使用Windows的任务管理器程序。但默认是只显示“非空闲”执行时间的百分比。在Windows 7任务管理器视图菜单里有“显示内核时间”这一项,这样的话,用户时间和内核时间就区分开了。内核时间是红色部分,如下图:
在编程上,使用性能计数器可以进行更详细的CPU时间监控。比如下面自己做一个CPU使用监控的程序:
使用的性能计数器是Processor类中的:
% Idle Time: 代表空闲% Interrupt Time: 代表处理硬件中断% User Time: 代表处理用户指令% Privileged Time: 代表操作系统内核指令% Processor Time: 代表所有非空闲时间(也是任务管理器默认显示的)
(所有上面的性能计数器返回百分比!)
你可以在控制面板的性能监控器中查看这些信息(或者在运行中键入:perfmon),如下图:
最后需要注意的一点就是PerformaceCounter类(System.Diagnostics命名空间内)的GetNextValue方法进行下一个值的获取步骤时,虽然该方法返回float,但这个百分比时是已经规格化好的,从0.0到100.0的,而不是0.0到1.0的。
3. 源代码下载
当前版本的程序和源代码下载
源代码环境:Visual C# Express 2010

参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:544095次
积分:5539
积分:5539
排名:第3914名
原创:19篇
转载:247篇
评论:46条
(1)(1)(1)(1)(1)(2)(1)(1)(7)(7)(6)(7)(6)(4)(10)(2)(7)(9)(1)(1)(1)(1)(4)(3)(9)(13)(1)(1)(4)(2)(2)(4)(10)(22)(2)(9)(8)(15)(11)(2)(12)(8)(13)(8)(14)(13)C#语言 &&&&最新内容
C#语言 &&&&随机内容I developed auto-call application.The App. read text file including phone number list and call for a few second and end call and repeat.
My problem is that App. do not send call after 10~16hours. I don't know the reason exactly,
But I guess that the problem is CPU usgae. My App's CPU usage is almost 50%!
How to reduce CPU usage?
Here is part of source code.
I'm sorry that my english is bad.
if(pareTo("0")!=0) {
while(index & repeat_count) {
count = 1;
time_count = 2;
while(count & map.length) {
performDial();
//start call
//end call
finishActivity(1);
TimeDelay("60");
// wait for 60sec
count = count + 2;
time_count = time_count + 2;
onBackPressed();
// press back button for calling next number
showCallLog();
finishActivity(0);
This is TimeDelay() source :
public void TimeDelay(String delayTime) {
saveTime = System.currentTimeMillis()/1000;
currentTime = 0;
dTime = Integer.parseInt(delayTime);
while(currentTime - saveTime & dTime) {
currentTime =
System.currentTimeMillis()/1000;
TimeDelay() repeat while loop for a few times.
解决方案 The reason it's using 50% of your CPU is that Android apparently won't let it use 100% of the CPU, which a loop like the one in your TimeDelay() ordinarily would. (Or else you have two CPUs and it is in fact using 100% of one CPU.) What you're doing is called a
and it should be obvious why continually checking a condition will use lots of CPU. So don't do that. Use Thread.sleep() instead. Your app will then use no CPU at all during the wait.
Also, for God's sake, why are you passing a string and then parseInting it, rather than just passing an Integer in the first place? :-)
本文地址: &
我公司开发的自动调用应用application.The。阅读文本文件,包括电话号码,并拨打了数第二和结束通话,并重复。我的问题是应用程序。不要送10?16小时后调用。我不知道原因究竟,但我想,这个问题是CPU usgae。我的应用程序的CPU占用率几乎是50%!如何降低CPU使用率?下面是源$ C $ C的一部分。我很抱歉,我的英语不好。 如果(pareTo(“0”)!= 0){
而(指数< REPEAT_COUNT){
time_count = 2;
而(COUNT< map.length){
performDial(); //调用启动
拒绝(); //结束通话
finishActivity(1);
纯滞后(“60”); //等待60秒
time_count = time_count + 2;
onBack pressed(); // preSS后退按钮调用一个数
showCallLog();
finishActivity(0);
} 这是纯滞后()来源: 公共无效纯滞后(字符串delayTime){
saveTime = System.currentTimeMillis的()/ 1000;
currentTime的= 0;
DTIME =的Integer.parseInt(delayTime);
而(currentTime的 -
saveTime< DTIME){
currentTime的= System.currentTimeMillis的()/ 1000;
} 纯滞后()重复while循环几次。 解决方案 它使用CPU的50%,其原因是,Android的显然不会让它使用CPU的100%,其中像在一个循环的纯滞后()通常会。 (否则你有两个CPU,它使用一个CPU的100%是事实。)你在做什么叫做的,它应该是显而易见的,为什么不断地检查条件将使用大量的CPU。所以,不要做。使用视频下载()来代替。然后,您的应用程序将在等待期间不使用CPU的。此外,偏偏,为什么你传递一个字符串,然后 parseInt函数 ING它,而不是仅仅通过一个整数摆在首位? : - )
本文地址: &
扫一扫关注官方微信}

我要回帖

更多关于 打开程序cpu占用高 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信