对于当前进程的性能计数器CPU使用率超过100 [英] Performance counter CPU usage for current process is more than 100

查看:1013
本文介绍了对于当前进程的性能计数器CPU使用率超过100的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要显示CPU利用率为我的多线程应用程序(在多核处理器的工作)。我希望收到接近任务管理器的数字。但我得到的数字超过100%。甚至超过500%以上。是的,我知道,比专柜的%处理器时间作为类的过程我需要分成 Environment.ProcessorCount NumberOfLogicalProcessors(同样为我的配置)。而500%是的这种操作后的结果的。我测试了与不同的硬件(酷睿i7,酷睿i5,酷睿2)和软件配置(的Windows 7 SP1的所有更新,Windows 2008 R2 SP1的所有更新)不同的计算机这个例子中,得到了同样的问题。

 公共静态类的SystemInfo 
{
私人静态过程_thisProc;
私人静态布尔HasData = FALSE;
私有静态的PerformanceCounter _processTimeCounter;

私有静态无效的init()
{
如果(HasData)
的回报;

如果(CheckForPerformanceCounterCategoryExist(过程))
{
_processTimeCounter =新的PerformanceCounter();
_processTimeCounter.CategoryName =过程;
_processTimeCounter.CounterName =%处理器时间;
_processTimeCounter.InstanceName = FindInstanceName(过程);
_processTimeCounter.NextValue();
}

MaximumCpuUsageForCurrentProcess = 0;
HasData = TRUE;
}

私人静态布尔CheckForPerformanceCounterCategoryExist(字符串categoryName)
{
返回PerformanceCounterCategory.Exists(类别名);
}

公共静态字符串FindInstanceName(字符串categoryName)
{
字符串结果=的String.Empty;
_thisProc = Process.GetCurrentProcess();

如果(!的ReferenceEquals(_thisProc,NULL))
{
如果(!String.IsNullOrEmpty(类别名))
{
如果(CheckForPerformanceCounterCategoryExist(类别名称))
{
类PerformanceCounterCategory =新PerformanceCounterCategory(类别名);
的String []实例= category.GetInstanceNames();
串processName = _thisProc.ProcessName;

如果(实例!= NULL)
{
的foreach(字符串实例的实例)
{
如果(instance.ToLower()。等于( processName.ToLower()))
{
结果=实例;
中断;
}
}
}
}
}
}
返回结果;
}

公共静态INT CpuUsageForCurrentProcess
{
得到
{
的init();

如果(!的ReferenceEquals(_processTimeCounter,NULL))
{
INT结果=(int)的_processTimeCounter.NextValue();
结果/ = Environment.ProcessorCount; // // NumberOfLogicalProcessors同我

如果(MaximumCpuUsageForCurrentProcess<结果)
MaximumCpuUsageForCurrentProcess =结果;

返回结果;
}
返回0;
}
}

公共静态INT MaximumCpuUsageForCurrentProcess {私人集;得到; }
}

和代码执行(你需要创建Windows窗体有两个labeles应用一BackgroundWorker的和一个按钮)

 私人无效backgroundWorker1_DoWork(对象发件人,DoWorkEventArgs E)
{
IList的<任务>任务=新的List<任务>();
的for(int i = 0;我小于10;我++)
{
任务T =新建任务(()=>
{
做{
如果(backgroundWorker1.CancellationPending)
中断;
},而(真);
});
t.Start();
tasks.Add(T);
}

任务displayProgress =新建任务(()=> {{做
如果(backgroundWorker1.CancellationPending)
中断;
backgroundWorker1.ReportProgress (1);
Thread.sleep代码(10);
}当(真);});
displayProgress.Start();
tasks.Add(displayProgress);

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

私人无效backgroundWorker1_ProgressChanged(对象发件人,ProgressChangedEventArgs E)
{
label1.Text = SystemInfo.CpuUsageForCurrentProcess.ToString();
label2.Text = SystemInfo.MaximumCpuUsageForCurrentProcess.ToString();
}

私人无效的button1_Click(对象发件人,EventArgs五)
{
label1.Text = SystemInfo.CpuUsageForCurrentProcess.ToString();

如果(backgroundWorker1.IsBusy)
backgroundWorker1.CancelAsync();
,否则
backgroundWorker1.RunWorkerAsync();
}

请告诉我我的错误。是的,我读的这篇文章,发现




\Process(...)\%处理器时间可以多达N * 100(其中N是CPU的数目),因为它增加了在所有的CPU的请求的过程的CPU占用率。



解决方案

(有点关系)的问题建议使用的 System.Diagnostics.Process.TotalProcessorTime System.Diagnostics.ProcessThread 。.TotalProcessorTime 属性,而不是为低开销,易于实现



(编辑:的这里的解释如何使用属性,以及一篇文章。)



此外,它看起来就像你没有等待足够长的时间调用之间_processTimeCounter.NextValue()。按照文档,你应该等待至少1第二。不知道这会导致你的陌生号码或没有。


I want to display CPU usage for my multithread application (working over multicore processor). I want to receive numbers close to Task manager's. But I got numbers more than 100%. Even more than 500%. Yes, I know, than counter "% Processor Time" for category "Process" I need to divide into Environment.ProcessorCount or "NumberOfLogicalProcessors" (same for my configuration). And 500% is a result after this operation. I tested this example on different computers with different hardware (i7, i5, Core2) and software configurations (Windows 7 SP1 with all updates, Windows 2008 R2 SP1 with all updates) and got same problem.

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; }
}

and code to execute (you need to create windows forms application with two labeles, one BackgroundWorker and one button)

    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();
    }

Please show me my error. And yes, I read this article and noticed that

"\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 (somewhat related) question suggests using the System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties instead, for low overhead and easy implementation.

(Edit: Here's an article explaining how to use the properties, as well.)

Also, it looks like you're not waiting long enough between calls to "_processTimeCounter.NextValue()." As per the documentation, you're supposed to wait at least 1 second. Not sure if that would cause your strange numbers or not.

这篇关于对于当前进程的性能计数器CPU使用率超过100的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆