简体   繁体   English

使用PerformanceCounter获取进程的CPU使用率

[英]Get CPU usage of process with PerformanceCounter

I'm trying to get the CPU usage of a specific process, but it returns just 0. I still don't know what the problem is. 我正在尝试获取特定进程的CPU使用率,但它仅返回0。我仍然不知道问题出在哪里。

Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
    if (GetProcessOwner(theprocess.Id) != "NO_OWNER")
    {
        if (theprocess.ProcessName != "svchost")
        {
            var ram = BytesToString(theprocess.PeakWorkingSet64);
            ram = ram.Replace("MB", "");

            string state = "";

            if (theprocess.MainWindowTitle == "") 
            {
                state = "background";
            }
            else 
            {
                state = "foreground";
            }

            sw.WriteLine("ID=" + theprocess.Id + "&NAME=" + theprocess.ProcessName + "&RAM=" + ram + "&STARTED=" + theprocess.StartTime + "&STATE=" + state);
            PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", theprocess.ProcessName);
            Console.WriteLine("CPU="+counter.NextValue());
        }
    }
}

It's okay, because NextValue always return 0 when you call it first time . 没关系,因为下次调用NextValue时始终返回0

For fix this error you can call NextValue function twice after creation PerformanceCounter object (durty hack). 为了解决此错误,您可以在创建PerformanceCounter对象(耐用性黑客)后两次调用NextValue函数。

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

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