平均CPU使用率问题 [英] Average CPU usage question

查看:95
本文介绍了平均CPU使用率问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助...

我正在尝试使用我在多个论坛上拼凑的代码,在5秒的时间内读取平均CPU使用率,但我正在努力...

到目前为止的代码

Please help...

I am trying to get an average CPU usage reading over a 5 second time-slice using code I have cobbled together from multiple forums but I am struggling...

Code so far

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.Timers;
using System.Threading;


namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
            {
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 2000;
            aTimer.Enabled = true;
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
            }  
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
               PerformanceCounter CPU = new PerformanceCounter("Processor", "% Processor Time", "_Total"); 
// I would like to get 5 samples of CPU and then calculate an average e.g. CPUTotal = (CPU1 + CPU2 + CPU3 + CPU4 + CPU5) / 5
//   console.writeline(CPUTotal + "%");
        }
    }
}



请帮忙吗?



Any help please?

推荐答案

试一下这样的东西.
如果您坚持使用计时器,请将性能计数器的结果存储在某个地方,然后再进行计算.

Play around with something like this.
If you insist on using a timer, store the result of your perf-counter somewhere and calculate it later.

static void Main( string[] args )
{
    PerformanceCounter perfCounter = new PerformanceCounter( "Processor", "% Processor Time", "_Total" );
    float sum = 0;
    int rounds = 0;
    while ( rounds < 5 )
    {
        sum += perfCounter.NextValue();
        Thread.Sleep( 1000 );
        ++rounds;
    }

    perfCounter.Close();
    perfCounter.Dispose();

    Console.Out.WriteLine( sum / rounds );
    Console.Out.WriteLine( "Done" );
    Console.Read();
}


如何获取进程和线程的CPU使用率 [ ^ ]


@shoputer

计时器在那里,因此它可以每x分钟收集许多指标,例如.每10分钟获取5个样本的平均CPU使用率,可用的RAM等.

因此,如果我理解正确,总和/轮数=轮次中的平均CPU使用率?
例如第1轮的CPU使用率= 0%(始终在第一个样本中),第2轮的CPU使用率= 5%,第3轮的CPU使用率= 7%.超过3轮的总次数= 12%,除以3轮= 4%的平均使用量?

另外,如何在3个回合后继续关闭采样"?
@shoputer

The timer is there so that it can collect a number of metrics every x minutes eg. every 10 minutes get the average CPU usage of 5 samples, get the available RAM etc. etc.

So, if I understand correctly, sum/rounds = the average CPU usage over the rounds?
e.g. Round 1 cpu usage = 0% (it always is on the first sample), Round 2 cpu usage = 5%, Round 3 cpu usage = 7%. Total over 3 rounds = 12%, divide by 3 rounds = 4% average usage?

Also, how do I get the "sampling" to close as it keeps going after 3 rounds?


这篇关于平均CPU使用率问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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