c# - 当前进程的性能计数器 CPU 使用率超过 100

标签 c# process cpu-usage performancecounter

我想显示我的多线程应用程序(在多核处理器上工作)的 CPU 使用情况。我想收到接近任务管理器的号码。但我得到的数字超过 100%。甚至超过500%。是的,我知道,对于类别"Process" 的计数器"% Processor Time" 我需要划分为Environment.ProcessorCount “NumberOfLogicalProcessors”(与我的配置相同)。而 500% 是此操作之后的结果。我在具有不同硬件(i7、i5、Core2)和软件配置(具有所有更新的 Windows 7 SP1、具有所有更新的 Windows 2008 R2 SP1)的不同计算机上测试了这个示例,但遇到了同样的问题。

public static class SystemInfo
{
    private static Process _thisProc;
    private static bool HasData = false;
    private static PerformanceCounter _processTimeCounter;

    private static void Init()
    {
        if (HasData)
            return;

        if (CheckForPerformanceCounterCategoryExist("Process"))
        {
            _processTimeCounter = new PerformanceCounter();
            _processTimeCounter.CategoryName = "Process";
            _processTimeCounter.CounterName = "% Processor Time";
            _processTimeCounter.InstanceName = FindInstanceName("Process");
            _processTimeCounter.NextValue();
        }

        MaximumCpuUsageForCurrentProcess = 0;
        HasData = true;
    }

    private static bool CheckForPerformanceCounterCategoryExist(string categoryName)
    {
        return PerformanceCounterCategory.Exists(categoryName);
    }

    public static string FindInstanceName(string categoryName)
    {
        string result = String.Empty;
        _thisProc = Process.GetCurrentProcess();

        if (!ReferenceEquals(_thisProc, null))
        {
            if (!String.IsNullOrEmpty(categoryName))
            {
                if (CheckForPerformanceCounterCategoryExist(categoryName))
                {
                    PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName);
                    string[] instances = category.GetInstanceNames();
                    string processName = _thisProc.ProcessName;

                    if (instances != null)
                    {
                        foreach (string instance in instances)
                        {
                            if (instance.ToLower().Equals(processName.ToLower()))
                            {
                                result = instance;
                                break;
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    public static int CpuUsageForCurrentProcess
    {
        get
        {
            Init();

            if (!ReferenceEquals(_processTimeCounter, null))
            {
                int result = (int) _processTimeCounter.NextValue();
                result /= Environment.ProcessorCount; //NumberOfLogicalProcessors //same for me

                if (MaximumCpuUsageForCurrentProcess < result)
                    MaximumCpuUsageForCurrentProcess = result;

                return result;
            }
            return 0;
        }
    }

    public static int MaximumCpuUsageForCurrentProcess { private set; get; }
}

和要执行的代码(您需要创建具有两个标签、一个 BackgroundWorker 和一个按钮的 Windows 窗体应用程序)

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        IList<Task> tasks = new List<Task>();
        for (int i = 0; i < 10; i++)
        {
            Task t = new Task(() =>
            {
                do {
                    if (backgroundWorker1.CancellationPending)
                        break;
                } while (true);
            });
            t.Start();
            tasks.Add(t);
        }

        Task displayProgress = new Task(() => { do {
                                                    if (backgroundWorker1.CancellationPending)
                                                        break;
                                                    backgroundWorker1.ReportProgress(1);
                                                    Thread.Sleep(10);
                                                } while (true); });
        displayProgress.Start();
        tasks.Add(displayProgress);

        Task.WaitAll(tasks.ToArray());
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        label1.Text = SystemInfo.CpuUsageForCurrentProcess.ToString();
        label2.Text = SystemInfo.MaximumCpuUsageForCurrentProcess.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = SystemInfo.CpuUsageForCurrentProcess.ToString();

        if (backgroundWorker1.IsBusy)
            backgroundWorker1.CancelAsync();
        else
            backgroundWorker1.RunWorkerAsync();
    }

请告诉我我的错误。是的,我读了this article并注意到

“\Process(…)\% Processor Time” can go up to N*100 (where N is the number of CPUs) because it adds up the CPU usage of the requested process across all the CPUs.

最佳答案

This (有点相关)问题建议使用 System.Diagnostics.Process.TotalProcessorTimeSystem.Diagnostics.ProcessThread.TotalProcessorTime属性,以实现低开销和易于实现。

(编辑:Here's an article 也解释了如何使用这些属性。)

此外,看起来您在调用“_processTimeCounter.NextValue()”之间等待的时间不够长。根据 the documentation ,您应该至少等待 1 秒钟。不确定这是否会导致您出现奇怪的号码。

关于c# - 当前进程的性能计数器 CPU 使用率超过 100,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9501645/

相关文章:

c# - Web 服务中的通用类型 WebMethod

C#如何在app.config文件中指定appData文件路径

c# - 我如何异步处理消息,在处理时丢弃任何新消息?

java - 在 Java 中创建动态代理抢走了 OS X 的焦点

c++ - FileServer 可以避免高 CPU 使用率吗?

c# - IE6 : window. onresize 在 IIS 上工作,在 asp.net 开发服务器上崩溃

vb.net - 检测exe何时启动vb.net

linux - 停止进程但堆仍在变化

linux - 如何在 Linux 中限制 Matlab 的 CPU 使用率

linux - 如何在多核系统上获取 CPU 使用率