C#从特定进程获取CPU和RAM(性能计数器)

时间:2012-01-28 19:18:34

标签: c# process cpu monitor performancecounter

我想检索当前进程(或特定进程)的cpu和ram使用情况。 检索窗口的标题不是问题,而且该部分有效。但即使活动窗口以70%或更高的CPU运行,cpu显示仍保持在0%。

(INT)pCPU.NextValue(); //<<<<不断返回0 ...

注意:我想用性能计数器来做。我不想使用Process变量来执行它,因为那可能会引发“权限错误不足”。

    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);

    public void GetActiveCPUAndRam(out string windowTitle, out int CPUUsagePerc, out int RAMUsage)
    {
        IntPtr hwnd = GetForegroundWindow();
        uint pid;
        GetWindowThreadProcessId(hwnd, out pid);

        Process activeProc = Process.GetProcessById((int) pid);

        #region Window Title

        const int nChars = 256;
        StringBuilder Buff = new StringBuilder(nChars);
        if (GetWindowText(hwnd, Buff, nChars) > 0)
            windowTitle = Buff.ToString();
        else
        {
            windowTitle = "";
            CPUUsagePerc = 0;
            RAMUsage = 0;
            return;
        }

        #endregion

        #region RAM/CPU
        PerformanceCounter pCPU = new PerformanceCounter("Process", "% Processor Time", activeProc.ProcessName, true);
        pCPU.NextValue();
        CPUUsagePerc = (int)pCPU.NextValue(); // <<<<< problem here.

        RAMUsage = 0; // TODO:

        #endregion
    }



编辑: 我尝试了新的解决方案: 但是,当我运行一个cpu压力测试程序,将CPU使用率推到100%(单核)。然后下面的解决方案显示该进程的cpu使用率就像cpu总量的300-400%......显然还有一些问题。


        private PerformanceCounter pCPU = null;
        private IntPtr PreviousProcHwnd = IntPtr.Zero;
        private CounterSample PreviousCPUCounterSample = CounterSample.Empty;

        public void GetActiveCPUAndRam(out string windowTitle, out int CPUUsagePerc, out int RAMUsage)
{
        ...
        #region RAM/CPU

        if (PreviousProcHwnd != hwnd)
        {
            PreviousProcHwnd = hwnd;
            pCPU = new PerformanceCounter("Process", "% Processor Time", activeProc.ProcessName,
                                                             true);
            PreviousCPUCounterSample = CounterSample.Empty;
        }

        CounterSample sample1 = pCPU.NextSample();
        CPUUsagePerc = (int)CounterSample.Calculate(PreviousCPUCounterSample, sample1);
        PreviousCPUCounterSample = sample1;
        RAMUsage = 0; // TODO:

        #endregion
}

1 个答案:

答案 0 :(得分:0)

请勿直接使用该值,请使用计算出的样本

CounterSample sample1 = pCPU.NextSample();
float value = CounterSample.Calculate(sample1);

如果您的计数器是'费率'类型样本,那么您需要获得两个样本,

CounterSample sample1 = counter.NextSample();
Thread.Sleep(1000); // wait some time
CounterSample sample2 = counter.NextSample();
float value = CounterSample.Calculate(sample1, sample2);