一 PerformanceCounter 基本介绍
1 简单介绍
表示 Windows NT 性能计数器组件 
命名空间:System.Diagnostics
程序集:System(在 system.dll 中)
2 构造函数(只介绍本文要用到的)
PerformanceCounter (String, String, String) 
功能:
初始化 PerformanceCounter 类的新的只读实例,
并将其与本地计算机上指定的系统性能计数器或自定义性能计数器及类别实例关联
参数说明:
public PerformanceCounter (
 string categoryName,
 string counterName,
 string instanceName
)
categoryName
性能计数器关联的性能计数器类别(性能对象)的名称。 
counterName
性能计数器的名称。 
instanceName
性能计数器类别实例的名称,或者为空字符串 ("")(如果该类别包含单个实例)。
二 示例方法:
需要引用命名空间

using System.Diagnostics;
using System.Threading;
using System.Collections;

1 获取性能计数器类别列表
虽然系统中有很多可用的计数器类别,但与之交互最频繁的可能是“Cache”(缓存)、“Memory”(内存)、
“Objects”(对象)

、“PhysicalDisk”(物理磁盘)、“Process”(进程)、“Processor”(处理器)、
“Server”(服务器)、“System”(系统)和“Thread”(线程)等类别

        public static void GetCategoryNameList()
        {
            PerformanceCounterCategory[] myCat2;
            myCat2 = PerformanceCounterCategory.GetCategories();
            for (int i = 0; i < myCat2.Length; i++)
            {
                Console.WriteLine(myCat2[i].CategoryName.ToString());
            }
        }

2 获取性能计数器类别下的实例的名称实例下的性能计数器的名称

        public static void GetInstanceNameListANDCounterNameList(string CategoryName)
        {
            string[] instanceNames;
            ArrayList counters = new ArrayList();
            PerformanceCounterCategory mycat = new PerformanceCounterCategory(CategoryName);
            try
            {
                instanceNames = mycat.GetInstanceNames();
                if (instanceNames.Length == 0)
                {
                    counters.AddRange(mycat.GetCounters());
                }
                else
                {
                    for (int i = 0; i < instanceNames.Length; i++)
                    {
                        counters.AddRange(mycat.GetCounters(instanceNames[i]));
                    }
                }
                for (int i = 0; i < instanceNames.Length; i++)
                {
                    Console.WriteLine(instanceNames[i]);
                }
                Console.WriteLine("******************************");
                foreach (PerformanceCounter counter in counters)
                {
                    Console.WriteLine(counter.CounterName);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to list the counters for this category");
            }
        }

3 根据categoryName,counterName,instanceName获得性能情况显示

        private static void PerformanceCounterFun(string CategoryName, string InstanceName, string CounterName)
        {
            PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName);
            while (true)
            {
                Thread.Sleep(1000); // wait for 1 second 
                float cpuLoad = pc.NextValue();
                Console.WriteLine("CPU load = " + cpuLoad + " %.");
            }
        }

4 调用方法3显示cpu使用率

PerformanceCounterFun("Processor", "_Total", "% Processor Time");

Performance Counter的使用

 

客户端性能测试通过performanceCounter监控客户端性能指标

PerformanceCounter PTCounter = new PerformanceCounter("Process",
                                        "% Processor Time",
                                         "AliIM");
            logfile("% Processor Time:" + PTCounter.NextValue().ToString());
            //内存
            PerformanceCounter WSCounter = new PerformanceCounter("Process",
                                                                    "Working Set",
                                                                     "AliIM");
            logfile("Working Set:" + ((double)WSCounter.NextValue() / 1024).ToString());

//内存最高值
            PerformanceCounter MemeryCounter = new PerformanceCounter("Process",
                                                                    "Working Set Peak",
                                                                     "AliIM");
            logfile("Working Set Peak:" + ((double)MemeryCounter.NextValue() / 1024).ToString());

//虚拟内存
            PerformanceCounter PBCounter = new PerformanceCounter("Process",
                                                              "Private Bytes",
                                                               "AliIM");
            logfile("Private Bytes:" + ((double)PBCounter.NextValue() / 1024).ToString());

//句柄数
            PerformanceCounter HCCounter = new PerformanceCounter("Process",
                                                  "Handle Count",
                                                   "AliIM");
            logfile("Handle Count:" + HCCounter.NextValue() .ToString());

//线程数Thread Count
            PerformanceCounter TCCounter = new PerformanceCounter("Process",
                                      "Thread Count",
                                       "AliIM");
            logfile("Thread Count:" + TCCounter.NextValue() .ToString());

//补充得到GDI OBJECTS

Process process;
            process = System.Diagnostics.Process.GetProcessesByName("AliIM")[0];
            
            logfile("GDI Objects Count:" + GetGuiResources(process.Handle, 0));

[DllImport("User32")]

extern public static int GetGuiResources(IntPtr hProcess, int uiFlags);

通过编码方式使用性能计数器来进行性能计数的一个简单例子

比如我们有这样一个需求:
我要编码方式记录我们当前编写的程序每秒钟抛出异常数

如果我们直接使用 Performance 工具,就是采用下图方式依次选择:

1、选择要做性能测试的计算机
2、选择要用那个 Proformance object; 这里我们选择: .NET CLR Exceptions
3、选择 需要的计数项,这里我们选 # of Exceps Thrown / sec
4、选择你要对那个程序进行测试(也就是那个进程产生的异常),在这里就请选择你要测试的程序名字

如果我们希望用编码方式来实现这个功能的话,也很简单:
System.Diagnostics.PerformanceCounter 就是编码获得性能计数的核心
这部分的代码如下:

System.Diagnostics.PerformanceCounter pc = new PerformanceCounter();

// 获取或设置此性能计数器的性能计数器类别的名称。

pc.CategoryName = ".NET CLR Exceptions";

// 获取或设置与此 PerformanceCounter 实例关联的性能计数器的名称。

pc.CounterName = "# of Exceps Thrown / sec";

// 获取或设置此性能计数器的实例名称。

pc.InstanceName =

System.IO.Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.SetupInformation.ApplicationName);

pc.ReadOnly = true;

Console.WriteLine(pc.RawValue);

Console.WriteLine(pc.NextValue());

int num = 30;

for (int i = 0; i < num; i++)

{

try

{

throw new Exception("test Exception");

}

catch (Exception)

{

}

}

// 获取或设置此计数器的原始值(即未经过计算的值)。

Console.WriteLine(pc.RawValue);

// 获取计数器样本并为其返回计算所得值。

Console.WriteLine(pc.NextValue());

Console.WriteLine("===========");

上述代码只是一个超简单的例子,实际性能计数可以写得比这个更复杂。 
这时候,你可以参考以下几个类:

说明

System.Diagnostics.PerformanceCounter

表示 Windows NT 性能计数器组件。使用该类读取现有预定义的或自定义的计数器并向自定义计数器发布(写入)性能数据。

System.Diagnostics.PerformanceCounterCategory

提供与计数器交互的几种方法以及该计算机上计数器的类别。

System.Diagnostics.PerformanceCounterInstaller

指定 PerformanceCounter 组件的安装程序。

System.Diagnostics.PerformanceCounterType

指定用于计算 PerformanceCounter 的NextValue 方法的公式。

附:

我们这个例子中需要做的性能计数器:

# of Exceps Thrown / Sec(引发的异常数/秒)

显示每秒引发的异常的数目。它包括 .NET 异常和转换成 .NET 异常的非托管异常。例如,从非托管代码返回的 HRESULT 转换为托管代码中的异常。
此计数器包括已处理和未处理的异常。此计数器不是一段时间内的平均值;它显示在最后两个样本(以取样间隔持续时间来划分)中观察到的值之间的差异。此计数器是一个潜在性能问题(如果引发多于 100 个的较多数目的异常)的指示器。

Performance Counter的使用误区

2008-07-11 20:42

很多人在使用PerfomanceCounter的时候直接new PerfomanceCounter实例,然后就去调用NextValue()方法。这样往往得到的值是0.00,今天我也犯了这么错误,找个了半天,终于发现,performance counter在计算值得时候,需要两个样本,如果我们获取到PerformanceCounter后直接调用NextValue()方法,则只会获取到第一个样本的值,该值往往会是0。

下面告诉大家正确的代码是:
PerformanceCounter pc = new PerformanceCounter();
            pc.CategoryName = cataName;
            pc.CounterName = counter;
            pc.InstanceName = instance;
            pc.MachineName = ".";
            pc.ReadOnly = true;
            
           pc.NextValue();
            System.Threading.Thread.Sleep(1000); //等1秒,让后系统获取下一个样本

return pc.NextValue();

其实,如果你的对象不销毁,下次再获取的时候就不会为0了,也就不需要再sleep(1000),只要你两次调用NextValue的时间间隔大于1秒。

Performance Counter的使用——获取各类组件性能,获取CPU参数等的更多相关文章

  1. Performance Counter的使用

    原文地址:http://blog.csdn.net/jiangxinyu/article/details/5480401 PerformanceCounter 基本介绍以及示例方法 一 Perform ...

  2. 消息队列数量统计(MSMQ,Performance Counter)

    微软消息队列服务MSMQ (Microsoft Message Queue),工作在在线或者离线场景,并提供异步编程功能.互联网和企业开发很多场景应用,例如电商的订单处理流程,这是因为客户端不需要等待 ...

  3. PHP 获取linux服务器性能CPU、内存、硬盘、进程等使用率

    数据库配置文件: conn.php <?php define("MONITORED_IP", "172.16.0.191"); //被监控的服务器IP地址 ...

  4. [转帖]当 K8s 集群达到万级规模,阿里巴巴如何解决系统各组件性能问题?

    改天学习一下. https://www.cnblogs.com/alisystemsoftware/p/11570806.html   当 K8s 集群达到万级规模,阿里巴巴如何解决系统各组件性能问题 ...

  5. React 组件性能优化

    React组件性能优化 前言 众所周知,浏览器的重绘和重排版(reflows & repaints)(DOM操作都会引起)才是导致网页性能问题的关键.而React虚拟DOM的目的就是为了减少浏 ...

  6. JSP第四篇【EL表达式介绍、获取各类数据、11个内置对象、执行运算、回显数据、自定义函数、fn方法库】

    什么是EL表达式? 表达式语言(Expression Language,EL),EL表达式是用"${}"括起来的脚本,用来更方便的读取对象! EL表达式主要用来读取数据,进行内容的 ...

  7. angular2的ElementRef在组件中获取不到

    angular2的ElementRef在组件中获取不到 angular2不推荐操作dom,但是实际应用中不可避免的需要使用到dom操作,怎么操作,官方文档提供了一系列api(ElementRef,Vi ...

  8. Vue 父组件ajax异步更新数据,子组件props获取不到

    转载 https://blog.csdn.net/d295968572/article/details/80810349 当父组件 axjos 获取数据,子组件使用 props 接收数据时,执行 mo ...

  9. react 使用 redux 的时候 用 ref获取子组件的state

    由于 redux是无状态的,所以当我们在子组件中使用了 redux的时候,再父组件中,使用  ref 来获取子组件的state时,发现为一个空对象. 其实这个是有解决方案法的,原因在于 我们使用的 r ...

随机推荐

  1. 发布的时候Archive灰色

    主要是因为发布的时候要选为将模拟器选择一下,选为Generic iOS Device. 来自为知笔记(Wiz)

  2. Android环境的搭建

    一.Java环境的配置(以JDK1.7为例) 在环境变量下查看,查看是否存在JAVA_HOME,没有的话新建一个 JAVA_HOME:java安装目录下jdk的安装目录 Path:jdk目录下面的bi ...

  3. Swift开发第四篇——柯里化

    本篇分为两部分: 一.柯里化的基本使用 二.柯里化的使用场景 一.柯里化的基本使用 柯里化(Currying):也就是把接受多个参数的方法变换成接受第一个参数的方法,并且返回接受余下的参数并且返回结果 ...

  4. RxJava结合Retrofit和Volley简单比较

    通过使用Retrofit+RxJava和Volley获取知乎日报消息,比较两者的使用区别. 文中 RR:代指Retrofit+Rxjava 主要两个方面使用 使用两者获取Json数据,使用Gson解析 ...

  5. IOS开发之功能模块--自定义UITabBarViewController的备用代码

    前言:因为常用,所以我就备份到这里,然后如果需要修改,可以根据需求进行相关的更改. @implementation YMTabBarController - (void)viewDidLoad { [ ...

  6. linux+jre+apache+mysql+tomcat调优

    一.不再为Apache进程淤积.耗尽内存而困扰 0. /etc/my.cnf,在mysqld那一段加上如下一行: log-slow-queries=queries-slow.log 重启MySQL 酌 ...

  7. INFORMATICA 的调优之 INFORMATICA SERVER TUNING

    INFORMATICA SERVER的调优我认为主要从两个级别来做,一个是MAPPING级别,一个是SESSION级别. 对于MAPPING级别的调优: 一  对MAPPING数据流向的优化: 1 控 ...

  8. CentOS 6.4安装配置LNMP服务器(Nginx+PHP+MySQL)

    准备篇 1.配置防火墙,开启80端口.3306端口 vi /etc/sysconfig/iptables-A INPUT -m state --state NEW -m tcp -p tcp --dp ...

  9. jsp中的四种对象作用域

    page:当前页面,也就是只要挑到别的页面就失效了,可以近似理解为java的this对象 request:一次会话,简单的理解就是一次请求范围内有效,例如如果通过forward方式跳转,则forwar ...

  10. Button未设type属性时在非IE6/7中具有submit特性

    代码如下 <!DOCTYPE html> <html> <head> <title>Button在Form中具有submit的特性</title& ...