System.Diagnostics.PerformanceCounterType 枚举
本文提供了此 API 参考文档的补充说明。
枚举 PerformanceCounterType 指定直接映射到本机类型的性能计数器类型。
某些计数器类型表示原始数据,而另一些计数器类型表示基于一个或多个计数器样本的计算值。 以下类别对可用的计数器类型进行分类。
- 平均值:测量一段时间内的值,并显示最后两个度量值的平均值。 跟踪所涉及的样本数的基本计数器与每个平均计数器相关联。
- 差异:从上一个度量值减去最后一个度量值,如果差值为正,则显示它;如果为负值,则显示零。
- 即时:显示最新的度量值。
- 百分比:将计算值显示为百分比。
- 速率:对随时间推移的事件计数进行采样,并将计数值的更改除以显示活动速率的时间变化。
采样性能计数器数据时,使用表示平均值的计数器类型可以使原始数据值对你的使用有意义。 例如,原始数据计数器 NumberOfItems64
可以公开从样本到样本相当随机的数据。 计数器返回的值的平均计算公式(X 0 +X 1 +...+X n)/n,其中每个 X i 都是原始计数器样本。
速率计数器类似于平均计数器,但对于使用资源时加息的情况更为有用。 快速计算平均值的公式是(X n -X 0)/(T n -T T 0)/频率,其中每个 X i 都是计数器样本,每个 T i 是相应样本的拍摄时间。 结果是每秒的平均使用量。
多时间器计数器 从组件的多个实例(例如处理器或磁盘)收集数据。
反向计数器 测量组件不处于活动状态的时间,并从该度量中派生活动时间。
注意
除非另有说明,否则基本时间为秒。
检测应用程序(创建和编写自定义性能计数器)时,你可能正在使用依赖于计算中使用的随附基计数器的性能计数器类型。 基本计数器必须在应用程序使用的集合中的 CounterCreationDataCollection 关联计数器之后立即完成。 下表列出了基计数器类型及其相应的性能计数器类型。
基计数器类型 | 性能计数器类型 |
---|---|
AverageBase |
AverageTimer32 AverageCount64 |
RawBase |
RawFraction |
CounterMultiBase |
CounterMultiTimer CounterMultiTimerInverse CounterMultiTimer100Ns CounterMultiTimer100NsInverse |
SampleBase |
SampleFraction |
以下是表示计算值的一些计数器使用的公式:
AverageCount64
:(N1 - N0)/(B1 - B0),其中 N 1 和 N 0 是性能计数器读取,B1 和 B0 是它们的对应AverageBase
值。 因此,分子表示在样本间隔期间处理的项数,分母表示样本间隔期间完成的操作数。AverageTimer32
:(N1 - N0)/F)/(B1 - B0),其中 N1 和 N0 是性能计数器读数,B1 和 B0 是它们的对应AverageBase
值,F 是每秒时钟周期数。 F 的值被考虑到公式中,以便结果可以以秒为单位显示。 因此,分析器表示在最后一个采样间隔期间计算的时钟周期数,F 表示时钟周期的频率,分母表示在最后一个样本间隔内完成的操作数。CounterDelta32
:N1 - N0,其中 N1 和 N0 是性能计数器读取。CounterDelta64
:N1 - N0,其中 N1 和 N0 是性能计数器读取。CounterMultiTimer
:(N1 - N0) / (D1 - D0)x 100 / B,其中 N1 和 N0 是性能计数器读取,D1 和 D0 是系统性能计时器的对应时间读数,变量 B 表示受监视组件的基数(使用类型的CounterMultiBase
基计数器)。 因此,分子表示监视组件处于活动状态的样本间隔部分,分母表示样本间隔的总运行时间。CounterMultiTimer100Ns
:(N1 - N0) / (D1 - D0)x 100 / B,其中 N1 和 N0 是性能计数器读数,D1 和 D0 是其 100 纳秒单位的对应时间读数,变量 B 表示受监视组件的基数(使用类型的CounterMultiBase
基计数器)。 因此,分子表示监视组件处于活动状态的样本间隔部分,分母表示样本间隔的总运行时间。CounterMultiTimer100NsInverse
:(B - (N1 - N0) / (D1 - D0))x 100,其中分母表示样本间隔的总已用时间,分子表示受监视组件处于非活动状态的时间间隔内的时间,B 表示所监视的组件数,使用类型的CounterMultiBase
基计数器。CounterMultiTimerInverse
:(B- (N1 - N0) / (D1 - D0))x 100,其中分母表示样本间隔的总运行时间,分析器表示受监视组件处于非活动状态的时间间隔内的时间,B 表示受监视的组件数,使用类型的CounterMultiBase
基计数器。CounterTimer
:(N1 - N0) / (D1 - D0),其中 N1 和 N0 是性能计数器读数,D1 和 D0 是相应的时间读数。 因此,分子表示监视组件处于活动状态的样本间隔部分,分母表示样本间隔的总运行时间。CounterTimerInverse
:(1- (N1 - N0) / (D1 - D0))x 100,其中分子表示受监视组件处于非活动状态的时间间隔内的时间,分母表示样本间隔的总运行时间。CountPerTimeInterval32
:(N1 - N0) / (D1 - D0),其中分子表示队列中的项数,分母表示在最后一个样本间隔期间经过的时间。CountPerTimeInterval64
:(N1 - N0) / (D1 - D0),其中分子表示队列中的项数,分母表示样本间隔期间经过的时间。ElapsedTime
:(D0 - N0) / F,其中 D0 表示当前时间,N0 表示对象启动的时间,F 表示以一秒为单位的时间单位数。 F 的值被考虑到公式中,以便结果可以以秒为单位显示。NumberOfItems32
:None。 不显示平均值,但显示收集的原始数据。NumberOfItems64
:None。 不显示平均值,但显示收集的原始数据。NumberOfItemsHEX32
:None。 不显示平均值,但显示收集的原始数据。NumberOfItemsHEX64
:None。 不显示平均值,但显示收集的原始数据RateOfCountsPerSecond32
:(N1 - N0) / ((D1 - D0) / F),其中 N1 和 N0 是性能计数器读数,D1 和 D0 是相应的时间读数,F 表示每秒时钟周期数。 因此,分析器表示在最后一个样本间隔期间执行的操作数,分母表示在最后一个样本间隔期间经过的刻度数,F 是时钟周期的频率。 F 的值被考虑到公式中,以便结果可以以秒为单位显示。RateOfCountsPerSecond64
:(N1 - N0) / ((D1 - D0) / F),其中 N1 和 N0 是性能计数器读数,D1 和 D0 是相应的时间读数,F 表示每秒时钟周期数。 因此,分析器表示在最后一个样本间隔期间执行的操作数,分母表示在最后一个样本间隔期间经过的刻度数,F 是时钟周期的频率。 F 的值被考虑到公式中,以便结果可以以秒为单位显示。RawFraction
:(N0/D0) x 100,其中 D0 表示度量属性(使用类型的RawBase
基计数器),N0 表示该特性的一个组件。SampleCounter
:(N1 - N0) / ((D1 - D0) / F),其中分子 (N) 表示已完成的操作数,分母 (D) 表示系统性能计时器的时钟周期单位的已用时间,F 表示一秒内经过的时钟周期数。 F 被考虑到公式中,以便结果可以以秒为单位显示。SampleFraction
:(N1 - N0) / (D1 - D0)x 100,其中,分子表示上一个样本间隔期间成功的操作数,分母表示在样本间隔期间完成的所有操作数(已测量的类型)的更改,使用类型的SampleBase
计数器。Timer100Ns
:(N1 - N0) / (D1 - D0) x 100,其中分子表示受监视组件处于活动状态的样本间隔部分,分母表示样本间隔的总运行时间。Timer100NsInverse
:(1- (N1 - N0) / (D1 - D0))x 100,其中分子表示受监视组件处于非活动状态的时间间隔内的时间,分母表示样本间隔的总运行时间。
示例
以下示例演示枚举中的 PerformanceCounterType 多个计数器类型。
AverageCount64
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Versioning;
[SupportedOSPlatform("Windows")]
public class App
{
private static PerformanceCounter avgCounter64Sample;
private static PerformanceCounter avgCounter64SampleBase;
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if (!PerformanceCounterCategory.Exists("AverageCounter64SampleCategory"))
{
CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData averageCount64 = new CounterCreationData();
averageCount64.CounterType = PerformanceCounterType.AverageCount64;
averageCount64.CounterName = "AverageCounter64Sample";
counterDataCollection.Add(averageCount64);
// Add the base counter.
CounterCreationData averageCount64Base = new CounterCreationData();
averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
averageCount64Base.CounterName = "AverageCounter64SampleBase";
counterDataCollection.Add(averageCount64Base);
// Create the category.
PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
"Demonstrates usage of the AverageCounter64 performance counter type.",
PerformanceCounterCategoryType.SingleInstance, counterDataCollection);
return (true);
}
else
{
Console.WriteLine("Category exists - AverageCounter64SampleCategory");
return (false);
}
}
private static void CreateCounters()
{
// Create the counters.
avgCounter64Sample = new PerformanceCounter("AverageCounter64SampleCategory",
"AverageCounter64Sample",
false);
avgCounter64SampleBase = new PerformanceCounter("AverageCounter64SampleCategory",
"AverageCounter64SampleBase",
false);
avgCounter64Sample.RawValue = 0;
avgCounter64SampleBase.RawValue = 0;
}
private static void CollectSamples(ArrayList samplesList)
{
Random r = new Random(DateTime.Now.Millisecond);
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
int value = r.Next(1, 10);
Console.Write(j + " = " + value);
avgCounter64Sample.IncrementBy(value);
avgCounter64SampleBase.Increment();
if ((j % 10) == 9)
{
OutputSample(avgCounter64Sample.NextSample());
samplesList.Add(avgCounter64Sample.NextSample());
}
else
{
Console.WriteLine();
}
System.Threading.Thread.Sleep(50);
}
}
private static void CalculateResults(ArrayList samplesList)
{
for (int i = 0; i < (samplesList.Count - 1); i++)
{
// Output the sample.
OutputSample((CounterSample)samplesList[i]);
OutputSample((CounterSample)samplesList[i + 1]);
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
// Description - This counter type shows how many items are processed, on average,
// during an operation. Counters of this type display a ratio of the items
// processed (such as bytes sent) to the number of operations completed. The
// ratio is calculated by comparing the number of items processed during the
// last interval to the number of operations completed during the last interval.
// Generic type - Average
// Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number
// of items processed during the last sample interval and the denominator (D)
// represents the number of operations completed during the last two sample
// intervals.
// Average (Nx - N0) / (Dx - D0)
// Example PhysicalDisk\ Avg. Disk Bytes/Transfer
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
{
Single numerator = (Single)s1.RawValue - (Single)s0.RawValue;
Single denomenator = (Single)s1.BaseValue - (Single)s0.BaseValue;
Single counterValue = numerator / denomenator;
return (counterValue);
}
// Output information about the counter sample.
private static void OutputSample(CounterSample s)
{
Console.WriteLine("\r\n+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.Versioning
<SupportedOSPlatform("Windows")>
Public Class App1
Private Shared avgCounter64Sample As PerformanceCounter
Private Shared avgCounter64SampleBase As PerformanceCounter
Public Shared Sub Main()
Dim samplesList As New ArrayList()
'If the category does not exist, create the category and exit.
'Performance counters should not be created and immediately used.
'There is a latency time to enable the counters, they should be created
'prior to executing the App1lication that uses the counters.
'Execute this sample a second time to use the counters.
If Not (SetupCategory()) Then
CreateCounters()
CollectSamples(samplesList)
CalculateResults(samplesList)
End If
End Sub
Private Shared Function SetupCategory() As Boolean
If Not PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") Then
Dim counterDataCollection As New CounterCreationDataCollection()
' Add the counter.
Dim averageCount64 As New CounterCreationData()
averageCount64.CounterType = PerformanceCounterType.AverageCount64
averageCount64.CounterName = "AverageCounter64Sample"
counterDataCollection.Add(averageCount64)
' Add the base counter.
Dim averageCount64Base As New CounterCreationData()
averageCount64Base.CounterType = PerformanceCounterType.AverageBase
averageCount64Base.CounterName = "AverageCounter64SampleBase"
counterDataCollection.Add(averageCount64Base)
' Create the category.
PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
"Demonstrates usage of the AverageCounter64 performance counter type.",
PerformanceCounterCategoryType.SingleInstance, counterDataCollection)
Return True
Else
Console.WriteLine("Category exists - AverageCounter64SampleCategory")
Return False
End If
End Function 'SetupCategory
Private Shared Sub CreateCounters()
' Create the counters.
avgCounter64Sample = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64Sample", False)
avgCounter64SampleBase = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64SampleBase", False)
avgCounter64Sample.RawValue = 0
avgCounter64SampleBase.RawValue = 0
End Sub
Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)
Dim r As New Random(DateTime.Now.Millisecond)
' Loop for the samples.
Dim j As Integer
For j = 0 To 99
Dim value As Integer = r.Next(1, 10)
Console.Write(j.ToString() + " = " + value.ToString())
avgCounter64Sample.IncrementBy(value)
avgCounter64SampleBase.Increment()
If j Mod 10 = 9 Then
OutputSample(avgCounter64Sample.NextSample())
samplesList.Add(avgCounter64Sample.NextSample())
Else
Console.WriteLine()
End If
System.Threading.Thread.Sleep(50)
Next j
End Sub
Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
Dim i As Integer
For i = 0 To (samplesList.Count - 1) - 1
' Output the sample.
OutputSample(CType(samplesList(i), CounterSample))
OutputSample(CType(samplesList((i + 1)), CounterSample))
' Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
' Calculate the counter value manually.
Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
Next i
End Sub
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
' Description - This counter type shows how many items are processed, on average,
' during an operation. Counters of this type display a ratio of the items
' processed (such as bytes sent) to the number of operations completed. The
' ratio is calculated by comparing the number of items processed during the
' last interval to the number of operations completed during the last interval.
' Generic type - Average
' Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number
' of items processed during the last sample interval and the denominator (D)
' represents the number of operations completed during the last two sample
' intervals.
' Average (Nx - N0) / (Dx - D0)
' Example PhysicalDisk\ Avg. Disk Bytes/Transfer
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
Private Shared Function MyComputeCounterValue(ByVal s0 As CounterSample, ByVal s1 As CounterSample) As [Single]
Dim numerator As [Single] = CType(s1.RawValue, [Single]) - CType(s0.RawValue, [Single])
Dim denomenator As [Single] = CType(s1.BaseValue, [Single]) - CType(s0.BaseValue, [Single])
Dim counterValue As [Single] = numerator / denomenator
Return counterValue
End Function 'MyComputeCounterValue
' Output information about the counter sample.
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
Console.WriteLine((" BaseValue = " + s.BaseValue.ToString()))
Console.WriteLine((" CounterFrequency = " + s.CounterFrequency.ToString()))
Console.WriteLine((" CounterTimeStamp = " + s.CounterTimeStamp.ToString()))
Console.WriteLine((" CounterType = " + s.CounterType.ToString()))
Console.WriteLine((" RawValue = " + s.RawValue.ToString()))
Console.WriteLine((" SystemFrequency = " + s.SystemFrequency.ToString()))
Console.WriteLine((" TimeStamp = " + s.TimeStamp.ToString()))
Console.WriteLine((" TimeStamp100nSec = " + s.TimeStamp100nSec.ToString()))
Console.WriteLine("++++++++++++++++++++++")
End Sub
End Class
AverageTimer32
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Versioning;
[SupportedOSPlatform("Windows")]
public class App2
{
private static PerformanceCounter PC;
private static PerformanceCounter BPC;
private const String categoryName = "AverageTimer32SampleCategory";
private const String counterName = "AverageTimer32Sample";
private const String baseCounterName = "AverageTimer32SampleBase";
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if (!PerformanceCounterCategory.Exists(categoryName))
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData averageTimer32 = new CounterCreationData();
averageTimer32.CounterType = PerformanceCounterType.AverageTimer32;
averageTimer32.CounterName = counterName;
CCDC.Add(averageTimer32);
// Add the base counter.
CounterCreationData averageTimer32Base = new CounterCreationData();
averageTimer32Base.CounterType = PerformanceCounterType.AverageBase;
averageTimer32Base.CounterName = baseCounterName;
CCDC.Add(averageTimer32Base);
// Create the category.
PerformanceCounterCategory.Create(categoryName,
"Demonstrates usage of the AverageTimer32 performance counter type",
PerformanceCounterCategoryType.SingleInstance, CCDC);
Console.WriteLine("Category created - " + categoryName);
return (true);
}
else
{
Console.WriteLine("Category exists - " + categoryName);
return (false);
}
}
private static void CreateCounters()
{
// Create the counters.
PC = new PerformanceCounter(categoryName,
counterName,
false);
BPC = new PerformanceCounter(categoryName,
baseCounterName,
false);
PC.RawValue = 0;
BPC.RawValue = 0;
}
private static void CollectSamples(ArrayList samplesList)
{
Random r = new Random(DateTime.Now.Millisecond);
// Loop for the samples.
for (int i = 0; i < 10; i++)
{
PC.RawValue = Stopwatch.GetTimestamp();
BPC.IncrementBy(10);
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Next value = " + PC.NextValue().ToString());
samplesList.Add(PC.NextSample());
}
}
private static void CalculateResults(ArrayList samplesList)
{
for (int i = 0; i < (samplesList.Count - 1); i++)
{
// Output the sample.
OutputSample((CounterSample)samplesList[i]);
OutputSample((CounterSample)samplesList[i + 1]);
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSample.Calculate((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
// PERF_AVERAGE_TIMER
// Description - This counter type measures the time it takes, on
// average, to complete a process or operation. Counters of this
// type display a ratio of the total elapsed time of the sample
// interval to the number of processes or operations completed
// during that time. This counter type measures time in ticks
// of the system clock. The F variable represents the number of
// ticks per second. The value of F is factored into the equation
// so that the result can be displayed in seconds.
//
// Generic type - Average
//
// Formula - ((N1 - N0) / F) / (D1 - D0), where the numerator (N)
// represents the number of ticks counted during the last
// sample interval, F represents the frequency of the ticks,
// and the denominator (D) represents the number of operations
// completed during the last sample interval.
//
// Average - ((Nx - N0) / F) / (Dx - D0)
//
// Example - PhysicalDisk\ Avg. Disk sec/Transfer
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
{
Int64 n1 = s1.RawValue;
Int64 n0 = s0.RawValue;
ulong f = (ulong)s1.SystemFrequency;
Int64 d1 = s1.BaseValue;
Int64 d0 = s0.BaseValue;
double numerator = (double)(n1 - n0);
double denominator = (double)(d1 - d0);
Single counterValue = (Single)((numerator / f) / denominator);
return (counterValue);
}
// Output information about the counter sample.
private static void OutputSample(CounterSample s)
{
Console.WriteLine("+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports System.Runtime.Versioning
<SupportedOSPlatform("Windows")>
Public Class App
Private Const categoryName As String = "AverageTimer32SampleCategory"
Private Const counterName As String = "AverageTimer32Sample"
Private Const baseCounterName As String = "AverageTimer32SampleBase"
Private Shared PC As PerformanceCounter
Private Shared BPC As PerformanceCounter
Public Shared Sub Main()
Dim samplesList As New ArrayList()
SetupCategory()
CreateCounters()
CollectSamples(samplesList)
CalculateResults(samplesList)
End Sub
Private Shared Function SetupCategory() As Boolean
If Not PerformanceCounterCategory.Exists(categoryName) Then
Dim CCDC As New CounterCreationDataCollection()
' Add the counter.
Dim averageTimer32 As New CounterCreationData()
averageTimer32.CounterType = PerformanceCounterType.AverageTimer32
averageTimer32.CounterName = counterName
CCDC.Add(averageTimer32)
' Add the base counter.
Dim averageTimer32Base As New CounterCreationData()
averageTimer32Base.CounterType = PerformanceCounterType.AverageBase
averageTimer32Base.CounterName = baseCounterName
CCDC.Add(averageTimer32Base)
' Create the category.
PerformanceCounterCategory.Create( _
categoryName, _
"Demonstrates usage of the AverageTimer32 performance counter type", _
PerformanceCounterCategoryType.SingleInstance, CCDC)
Console.WriteLine("Category created - " + categoryName)
Return True
Else
Console.WriteLine(("Category exists - " + _
categoryName))
Return False
End If
End Function
Private Shared Sub CreateCounters()
' Create the counters.
PC = New PerformanceCounter(categoryName, _
counterName, False)
BPC = New PerformanceCounter(categoryName, _
baseCounterName, False)
PC.RawValue = 0
BPC.RawValue = 0
End Sub
Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)
Dim r As New Random(DateTime.Now.Millisecond)
' Loop for the samples.
Dim i As Integer
For i = 0 To 9
PC.RawValue = Stopwatch.GetTimeStamp()
BPC.IncrementBy(10)
System.Threading.Thread.Sleep(1000)
Console.WriteLine(("Next value = " + PC.NextValue().ToString()))
samplesList.Add(PC.NextSample())
Next i
End Sub
Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
Dim i As Integer
Dim sample1 As CounterSample
Dim sample2 As CounterSample
For i = 0 To (samplesList.Count - 1) - 1
' Output the sample.
sample1 = CType(samplesList(i), CounterSample)
sample2 = CType(samplesList(i + 1), CounterSample)
OutputSample(sample1)
OutputSample(sample2)
' Use .NET to calculate the counter value.
Console.WriteLine((".NET computed counter value = " _
+ CounterSample.Calculate(sample1, sample2).ToString()))
' Calculate the counter value manually.
Console.WriteLine(("My computed counter value = " _
+ MyComputeCounterValue(sample1, sample2).ToString()))
Next i
End Sub
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
' PERF_AVERAGE_TIMER
' Description - This counter type measures the time it takes, on
' average, to complete a process or operation. Counters of this
' type display a ratio of the total elapsed time of the sample
' interval to the number of processes or operations completed
' during that time. This counter type measures time in ticks
' of the system clock. The F variable represents the number of
' ticks per second. The value of F is factored into the equation
' so that the result can be displayed in seconds.
'
' Generic type - Average
'
' Formula - ((N1 - N0) / F) / (D1 - D0), where the numerator (N)
' represents the number of ticks counted during the last
' sample interval, F represents the frequency of the ticks,
' and the denominator (D) represents the number of operations
' completed during the last sample interval.
'
' Average - ((Nx - N0) / F) / (Dx - D0)
'
' Example - PhysicalDisk\ Avg. Disk sec/Transfer
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
Private Shared Function MyComputeCounterValue( _
ByVal s0 As CounterSample, _
ByVal s1 As CounterSample) As Single
Dim n1 As Int64 = s1.RawValue
Dim n0 As Int64 = s0.RawValue
Dim f As Decimal = CType(s1.SystemFrequency, Decimal)
Dim d1 As Int64 = s1.BaseValue
Dim d0 As Int64 = s0.BaseValue
Dim numerator As Double = System.Convert.ToDouble(n1 - n0)
Dim denominator As Double = System.Convert.ToDouble(d1 - d0)
Dim counterValue As Single = CType(numerator, Single)
counterValue = counterValue / CType(f, Single)
counterValue = counterValue / CType(denominator, Single)
Return counterValue
End Function
' Output information about the counter sample.
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine("+++++++++++")
Console.WriteLine("Sample values - " + ControlChars.Cr _
+ ControlChars.Lf)
Console.WriteLine((" CounterType = " + _
s.CounterType.ToString()))
Console.WriteLine((" RawValue = " + _
s.RawValue.ToString()))
Console.WriteLine((" BaseValue = " _
+ s.BaseValue.ToString()))
Console.WriteLine((" CounterFrequency = " + _
s.CounterFrequency.ToString()))
Console.WriteLine((" CounterTimeStamp = " + _
s.CounterTimeStamp.ToString()))
Console.WriteLine((" SystemFrequency = " + _
s.SystemFrequency.ToString()))
Console.WriteLine((" TimeStamp = " + _
s.TimeStamp.ToString()))
Console.WriteLine((" TimeStamp100nSec = " + _
s.TimeStamp100nSec.ToString()))
Console.WriteLine("++++++++++++++++++++++")
End Sub
End Class
ElapsedTime
using System;
using System.Diagnostics;
using System.Runtime.Versioning;
[SupportedOSPlatform("Windows")]
public class App
{
public static void Main()
{
CollectSamples();
}
public static void CollectSamples()
{
const String categoryName = "ElapsedTimeSampleCategory";
const String counterName = "ElapsedTimeSample";
// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
if ( !PerformanceCounterCategory.Exists(categoryName) )
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData ETimeData = new CounterCreationData();
ETimeData.CounterType = PerformanceCounterType.ElapsedTime;
ETimeData.CounterName = counterName;
CCDC.Add(ETimeData);
// Create the category.
PerformanceCounterCategory.Create(categoryName,
"Demonstrates ElapsedTime performance counter usage.",
PerformanceCounterCategoryType.SingleInstance, CCDC);
// Return, rerun the application to make use of the new counters.
return;
}
else
{
Console.WriteLine("Category exists - {0}", categoryName);
}
// Create the performance counter.
PerformanceCounter PC = new PerformanceCounter(categoryName,
counterName,
false);
// Initialize the counter.
PC.RawValue = Stopwatch.GetTimestamp();
DateTime Start = DateTime.Now;
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
// Output the values.
if ((j % 10) == 9)
{
Console.WriteLine("NextValue() = " + PC.NextValue().ToString());
Console.WriteLine("Actual elapsed time = " + DateTime.Now.Subtract(Start).ToString());
OutputSample(PC.NextSample());
}
// Reset the counter on every 20th iteration.
if (j % 20 == 0)
{
PC.RawValue = Stopwatch.GetTimestamp();
Start = DateTime.Now;
}
System.Threading.Thread.Sleep(50);
}
Console.WriteLine("Elapsed time = " + DateTime.Now.Subtract(Start).ToString());
}
private static void OutputSample(CounterSample s)
{
Console.WriteLine("\r\n+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports System.Runtime.Versioning
<SupportedOSPlatform("Windows")>
Public Class App2
Public Shared Sub Main()
CollectSamples()
End Sub
Private Shared Sub CollectSamples()
Dim categoryName As String = "ElapsedTimeSampleCategory"
Dim counterName As String = "ElapsedTimeSample"
If Not PerformanceCounterCategory.Exists(categoryName) Then
Dim CCDC As New CounterCreationDataCollection()
' Add the counter.
Dim ETimeData As New CounterCreationData()
ETimeData.CounterType = PerformanceCounterType.ElapsedTime
ETimeData.CounterName = counterName
CCDC.Add(ETimeData)
' Create the category.
PerformanceCounterCategory.Create(categoryName,
"Demonstrates ElapsedTime performance counter usage.",
PerformanceCounterCategoryType.SingleInstance, CCDC)
Else
Console.WriteLine("Category exists - {0}", categoryName)
End If
' Create the counter.
Dim PC As PerformanceCounter
PC = New PerformanceCounter(categoryName, counterName, False)
' Initialize the counter.
PC.RawValue = Stopwatch.GetTimestamp()
Dim Start As DateTime = DateTime.Now
' Loop for the samples.
Dim j As Integer
For j = 0 To 99
' Output the values.
If j Mod 10 = 9 Then
Console.WriteLine(("NextValue() = " _
+ PC.NextValue().ToString()))
Console.WriteLine(("Actual elapsed time = " _
+ DateTime.Now.Subtract(Start).ToString()))
OutputSample(PC.NextSample())
End If
' Reset the counter every 20th iteration.
If j Mod 20 = 0 Then
PC.RawValue = Stopwatch.GetTimestamp()
Start = DateTime.Now
End If
System.Threading.Thread.Sleep(50)
Next j
Console.WriteLine(("Elapsed time = " +
DateTime.Now.Subtract(Start).ToString()))
End Sub
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++")
Console.WriteLine("Sample values - " + ControlChars.Cr _
+ ControlChars.Lf)
Console.WriteLine((" BaseValue = " _
+ s.BaseValue.ToString()))
Console.WriteLine((" CounterFrequency = " +
s.CounterFrequency.ToString()))
Console.WriteLine((" CounterTimeStamp = " +
s.CounterTimeStamp.ToString()))
Console.WriteLine((" CounterType = " +
s.CounterType.ToString()))
Console.WriteLine((" RawValue = " +
s.RawValue.ToString()))
Console.WriteLine((" SystemFrequency = " +
s.SystemFrequency.ToString()))
Console.WriteLine((" TimeStamp = " +
s.TimeStamp.ToString()))
Console.WriteLine((" TimeStamp100nSec = " +
s.TimeStamp100nSec.ToString()))
Console.WriteLine("+++++++")
End Sub
End Class
NumberOfItems32
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
public class NumberOfItems64
{
private static PerformanceCounter PC;
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if ( !PerformanceCounterCategory.Exists("NumberOfItems32SampleCategory") )
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData NOI64 = new CounterCreationData();
NOI64.CounterType = PerformanceCounterType.NumberOfItems64;
NOI64.CounterName = "NumberOfItems32Sample";
CCDC.Add(NOI64);
// Create the category.
PerformanceCounterCategory.Create("NumberOfItems32SampleCategory",
"Demonstrates usage of the NumberOfItems32 performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC);
return(true);
}
else
{
Console.WriteLine("Category exists - NumberOfItems32SampleCategory");
return(false);
}
}
private static void CreateCounters()
{
// Create the counter.
PC = new PerformanceCounter("NumberOfItems32SampleCategory",
"NumberOfItems32Sample",
false);
PC.RawValue=0;
}
private static void CollectSamples(ArrayList samplesList)
{
Random r = new Random( DateTime.Now.Millisecond );
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
int value = r.Next(1, 10);
Console.Write(j + " = " + value);
PC.IncrementBy(value);
if ((j % 10) == 9)
{
OutputSample(PC.NextSample());
samplesList.Add( PC.NextSample() );
}
else
{
Console.WriteLine();
}
System.Threading.Thread.Sleep(50);
}
}
private static void CalculateResults(ArrayList samplesList)
{
for(int i = 0; i < (samplesList.Count - 1); i++)
{
// Output the sample.
OutputSample( (CounterSample)samplesList[i] );
OutputSample( (CounterSample)samplesList[i+1] );
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i+1]) );
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i+1]) );
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
{
Single counterValue = s1.RawValue;
return(counterValue);
}
// Output information about the counter sample.
private static void OutputSample(CounterSample s)
{
Console.WriteLine("\r\n+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.Versioning
<SupportedOSPlatform("Windows")>
Public Class NumberOfItems64
Private Shared PC As PerformanceCounter
Public Shared Sub Main()
Dim samplesList As New ArrayList()
'If the category does not exist, create the category and exit.
'Performance counters should not be created and immediately used.
'There is a latency time to enable the counters, they should be created
'prior to executing the application that uses the counters.
'Execute this sample a second time to use the counters.
If Not (SetupCategory()) Then
CreateCounters()
CollectSamples(samplesList)
CalculateResults(samplesList)
End If
End Sub
Private Shared Function SetupCategory() As Boolean
If Not PerformanceCounterCategory.Exists("NumberOfItems32SampleCategory") Then
Dim CCDC As New CounterCreationDataCollection()
' Add the counter.
Dim NOI64 As New CounterCreationData()
NOI64.CounterType = PerformanceCounterType.NumberOfItems64
NOI64.CounterName = "NumberOfItems32Sample"
CCDC.Add(NOI64)
' Create the category.
PerformanceCounterCategory.Create("NumberOfItems32SampleCategory", _
"Demonstrates usage of the NumberOfItems32 performance counter type.", _
PerformanceCounterCategoryType.SingleInstance, CCDC)
Return True
Else
Console.WriteLine("Category exists - NumberOfItems32SampleCategory")
Return False
End If
End Function 'SetupCategory
Private Shared Sub CreateCounters()
' Create the counter.
PC = New PerformanceCounter("NumberOfItems32SampleCategory", "NumberOfItems32Sample", False)
PC.RawValue = 0
End Sub
Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)
Dim r As New Random(DateTime.Now.Millisecond)
' Loop for the samples.
Dim j As Integer
For j = 0 To 99
Dim value As Integer = r.Next(1, 10)
Console.Write(j.ToString() + " = " + value.ToString())
PC.IncrementBy(value)
If j Mod 10 = 9 Then
OutputSample(PC.NextSample())
samplesList.Add(PC.NextSample())
Else
Console.WriteLine()
End If
System.Threading.Thread.Sleep(50)
Next j
End Sub
Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
Dim i As Integer
For i = 0 To (samplesList.Count - 1) - 1
' Output the sample.
OutputSample(CType(samplesList(i), CounterSample))
OutputSample(CType(samplesList((i + 1)), CounterSample))
' Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
' Calculate the counter value manually.
Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
Next i
End Sub
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
Private Shared Function MyComputeCounterValue(ByVal s0 As CounterSample, ByVal s1 As CounterSample) As [Single]
Dim counterValue As [Single] = s1.RawValue
Return counterValue
End Function 'MyComputeCounterValue
' Output information about the counter sample.
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
Console.WriteLine(" BaseValue = " + s.BaseValue.ToString())
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency.ToString())
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp.ToString())
Console.WriteLine(" CounterType = " + s.CounterType.ToString())
Console.WriteLine(" RawValue = " + s.RawValue.ToString())
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency.ToString())
Console.WriteLine(" TimeStamp = " + s.TimeStamp.ToString())
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec.ToString())
Console.WriteLine("++++++++++++++++++++++")
End Sub
End Class
NumberOfItems64
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Versioning;
[SupportedOSPlatform("Windows")]
public class NumberOfItems64_1
{
private static PerformanceCounter PC;
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Perfomance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if (!PerformanceCounterCategory.Exists("NumberOfItems64SampleCategory"))
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData NOI64 = new CounterCreationData();
NOI64.CounterType = PerformanceCounterType.NumberOfItems64;
NOI64.CounterName = "NumberOfItems64Sample";
CCDC.Add(NOI64);
// Create the category.
PerformanceCounterCategory.Create("NumberOfItems64SampleCategory",
"Demonstrates usage of the NumberOfItems64 performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC);
return (true);
}
else
{
Console.WriteLine("Category exists - NumberOfItems64SampleCategory");
return (false);
}
}
private static void CreateCounters()
{
// Create the counters.
PC = new PerformanceCounter("NumberOfItems64SampleCategory",
"NumberOfItems64Sample",
false);
PC.RawValue = 0;
}
private static void CollectSamples(ArrayList samplesList)
{
Random r = new Random(DateTime.Now.Millisecond);
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
int value = r.Next(1, 10);
Console.Write(j + " = " + value);
PC.IncrementBy(value);
if ((j % 10) == 9)
{
OutputSample(PC.NextSample());
samplesList.Add(PC.NextSample());
}
else
{
Console.WriteLine();
}
System.Threading.Thread.Sleep(50);
}
}
private static void CalculateResults(ArrayList samplesList)
{
for (int i = 0; i < (samplesList.Count - 1); i++)
{
// Output the sample.
OutputSample((CounterSample)samplesList[i]);
OutputSample((CounterSample)samplesList[i + 1]);
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
{
Single counterValue = s1.RawValue;
return (counterValue);
}
// Output information about the counter sample.
private static void OutputSample(CounterSample s)
{
Console.WriteLine("\r\n+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.Versioning
<SupportedOSPlatform("Windows")>
Public Class NumberOfItems64_1
Private Shared PC As PerformanceCounter
Public Shared Sub Main()
Dim samplesList As New ArrayList()
'If the category does not exist, create the category and exit.
'Performance counters should not be created and immediately used.
'There is a latency time to enable the counters, they should be created
'prior to executing the application that uses the counters.
'Execute this sample a second time to use the counters.
If Not (SetupCategory()) Then
CreateCounters()
CollectSamples(samplesList)
CalculateResults(samplesList)
End If
End Sub
Private Shared Function SetupCategory() As Boolean
If Not PerformanceCounterCategory.Exists("NumberOfItems64SampleCategory") Then
Dim CCDC As New CounterCreationDataCollection()
' Add the counter.
Dim NOI64 As New CounterCreationData()
NOI64.CounterType = PerformanceCounterType.NumberOfItems64
NOI64.CounterName = "NumberOfItems64Sample"
CCDC.Add(NOI64)
' Create the category.
PerformanceCounterCategory.Create("NumberOfItems64SampleCategory",
"Demonstrates usage of the NumberOfItems64_1 performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC)
Return True
Else
Console.WriteLine("Category exists - NumberOfItems64SampleCategory")
Return False
End If
End Function 'SetupCategory
Private Shared Sub CreateCounters()
' Create the counters.
PC = New PerformanceCounter("NumberOfItems64SampleCategory", "NumberOfItems64Sample", False)
PC.RawValue = 0
End Sub
Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)
Dim r As New Random(DateTime.Now.Millisecond)
' Loop for the samples.
Dim j As Integer
For j = 0 To 99
Dim value As Integer = r.Next(1, 10)
Console.Write((j.ToString() + " = " + value.ToString()))
PC.IncrementBy(value)
If j Mod 10 = 9 Then
OutputSample(PC.NextSample())
samplesList.Add(PC.NextSample())
Else
Console.WriteLine()
End If
System.Threading.Thread.Sleep(50)
Next j
End Sub
Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
Dim i As Integer
For i = 0 To (samplesList.Count - 1) - 1
' Output the sample.
OutputSample(CType(samplesList(i), CounterSample))
OutputSample(CType(samplesList((i + 1)), CounterSample))
' Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
' Calculate the counter value manually.
Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
Next i
End Sub
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
Private Shared Function MyComputeCounterValue(ByVal s0 As CounterSample, ByVal s1 As CounterSample) As [Single]
Dim counterValue As [Single] = s1.RawValue
Return counterValue
End Function 'MyComputeCounterValue
' Output information about the counter sample.
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
Console.WriteLine((" BaseValue = " + s.BaseValue.ToString()))
Console.WriteLine((" CounterFrequency = " + s.CounterFrequency.ToString()))
Console.WriteLine((" CounterTimeStamp = " + s.CounterTimeStamp.ToString()))
Console.WriteLine((" CounterType = " + s.CounterType.ToString()))
Console.WriteLine((" RawValue = " + s.RawValue.ToString()))
Console.WriteLine((" SystemFrequency = " + s.SystemFrequency.ToString()))
Console.WriteLine((" TimeStamp = " + s.TimeStamp.ToString()))
Console.WriteLine((" TimeStamp100nSec = " + s.TimeStamp100nSec.ToString()))
Console.WriteLine("++++++++++++++++++++++")
End Sub
End Class
SampleFraction
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
// Provides a SampleFraction counter to measure the percentage of the user processor
// time for this process to total processor time for the process.
public class App
{
private static PerformanceCounter perfCounter;
private static PerformanceCounter basePerfCounter;
private static Process thisProcess = Process.GetCurrentProcess();
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if (!PerformanceCounterCategory.Exists("SampleFractionCategory"))
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData sampleFraction = new CounterCreationData();
sampleFraction.CounterType = PerformanceCounterType.SampleFraction;
sampleFraction.CounterName = "SampleFractionSample";
CCDC.Add(sampleFraction);
// Add the base counter.
CounterCreationData sampleFractionBase = new CounterCreationData();
sampleFractionBase.CounterType = PerformanceCounterType.SampleBase;
sampleFractionBase.CounterName = "SampleFractionSampleBase";
CCDC.Add(sampleFractionBase);
// Create the category.
PerformanceCounterCategory.Create("SampleFractionCategory",
"Demonstrates usage of the SampleFraction performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC);
return (true);
}
else
{
Console.WriteLine("Category exists - SampleFractionCategory");
return (false);
}
}
private static void CreateCounters()
{
// Create the counters.
perfCounter = new PerformanceCounter("SampleFractionCategory",
"SampleFractionSample",
false);
basePerfCounter = new PerformanceCounter("SampleFractionCategory",
"SampleFractionSampleBase",
false);
perfCounter.RawValue = thisProcess.UserProcessorTime.Ticks;
basePerfCounter.RawValue = thisProcess.TotalProcessorTime.Ticks;
}
private static void CollectSamples(ArrayList samplesList)
{
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
perfCounter.IncrementBy(thisProcess.UserProcessorTime.Ticks);
basePerfCounter.IncrementBy(thisProcess.TotalProcessorTime.Ticks);
if ((j % 10) == 9)
{
OutputSample(perfCounter.NextSample());
samplesList.Add(perfCounter.NextSample());
}
else
{
Console.WriteLine();
}
System.Threading.Thread.Sleep(50);
}
}
private static void CalculateResults(ArrayList samplesList)
{
for (int i = 0; i < (samplesList.Count - 1); i++)
{
// Output the sample.
OutputSample((CounterSample)samplesList[i]);
OutputSample((CounterSample)samplesList[i + 1]);
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
// Description - This counter type provides A percentage counter that shows the
// average ratio of user proccessor time to total processor time during the last
// two sample intervals.
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
{
Single numerator = (Single)s1.RawValue - (Single)s0.RawValue;
Single denomenator = (Single)s1.BaseValue - (Single)s0.BaseValue;
Single counterValue = 100 * (numerator / denomenator);
return (counterValue);
}
// Output information about the counter sample.
private static void OutputSample(CounterSample s)
{
Console.WriteLine("\r\n+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.Versioning
' Provides a SampleFraction counter to measure the percentage of the user processor
' time for this process to total processor time for the process.
<SupportedOSPlatform("Windows")>
Public Class App3
Private Shared perfCounter As PerformanceCounter
Private Shared basePerfCounter As PerformanceCounter
Private Shared thisProcess As Process = Process.GetCurrentProcess()
Public Shared Sub Main()
Dim samplesList As New ArrayList()
' If the category does not exist, create the category and exit.
' Performance counters should not be created and immediately used.
' There is a latency time to enable the counters, they should be created
' prior to executing the application that uses the counters.
' Execute this sample a second time to use the category.
If SetupCategory() Then
Return
End If
CreateCounters()
CollectSamples(samplesList)
CalculateResults(samplesList)
End Sub
Private Shared Function SetupCategory() As Boolean
If Not PerformanceCounterCategory.Exists("SampleFractionCategory") Then
Dim CCDC As New CounterCreationDataCollection()
' Add the counter.
Dim sampleFraction As New CounterCreationData()
sampleFraction.CounterType = PerformanceCounterType.SampleFraction
sampleFraction.CounterName = "SampleFractionSample"
CCDC.Add(sampleFraction)
' Add the base counter.
Dim sampleFractionBase As New CounterCreationData()
sampleFractionBase.CounterType = PerformanceCounterType.SampleBase
sampleFractionBase.CounterName = "SampleFractionSampleBase"
CCDC.Add(sampleFractionBase)
' Create the category.
PerformanceCounterCategory.Create("SampleFractionCategory", "Demonstrates usage of the SampleFraction performance counter type.", PerformanceCounterCategoryType.SingleInstance, CCDC)
Return True
Else
Console.WriteLine("Category exists - SampleFractionCategory")
Return False
End If
End Function 'SetupCategory
Private Shared Sub CreateCounters()
' Create the counters.
perfCounter = New PerformanceCounter("SampleFractionCategory", "SampleFractionSample", False)
basePerfCounter = New PerformanceCounter("SampleFractionCategory", "SampleFractionSampleBase", False)
perfCounter.RawValue = thisProcess.UserProcessorTime.Ticks
basePerfCounter.RawValue = thisProcess.TotalProcessorTime.Ticks
End Sub
Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)
' Loop for the samples.
Dim j As Integer
For j = 0 To 99
perfCounter.IncrementBy(thisProcess.UserProcessorTime.Ticks)
basePerfCounter.IncrementBy(thisProcess.TotalProcessorTime.Ticks)
If j Mod 10 = 9 Then
OutputSample(perfCounter.NextSample())
samplesList.Add(perfCounter.NextSample())
Else
Console.WriteLine()
End If
System.Threading.Thread.Sleep(50)
Next j
End Sub
Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
Dim i As Integer
For i = 0 To (samplesList.Count - 1)
' Output the sample.
OutputSample(CType(samplesList(i), CounterSample))
OutputSample(CType(samplesList((i + 1)), CounterSample))
' Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)))
' Calculate the counter value manually.
Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)))
Next i
End Sub
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
' Description - This counter type provides A percentage counter that shows the
' average ratio of user proccessor time to total processor time during the last
' two sample intervals.
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
Private Shared Function MyComputeCounterValue(ByVal s0 As CounterSample, ByVal s1 As CounterSample) As [Single]
Dim numerator As [Single] = CType(s1.RawValue, [Single]) - CType(s0.RawValue, [Single])
Dim denomenator As [Single] = CType(s1.BaseValue, [Single]) - CType(s0.BaseValue, [Single])
Dim counterValue As [Single] = 100 * (numerator / denomenator)
Return counterValue
End Function 'MyComputeCounterValue
' Output information about the counter sample.
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine(vbCr + vbLf + "+++++++++++")
Console.WriteLine("Sample values - " + vbCr + vbLf)
Console.WriteLine(" BaseValue = " + s.BaseValue)
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency)
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp)
Console.WriteLine(" CounterType = " + s.CounterType)
Console.WriteLine(" RawValue = " + s.RawValue)
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency)
Console.WriteLine(" TimeStamp = " + s.TimeStamp)
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec)
Console.WriteLine("++++++++++++++++++++++")
End Sub
End Class
RateOfCountsPerSecond32
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Versioning;
[SupportedOSPlatform("Windows")]
public class App3
{
private static PerformanceCounter PC;
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Perfomance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if (!PerformanceCounterCategory.Exists("RateOfCountsPerSecond32SampleCategory"))
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData rateOfCounts32 = new CounterCreationData();
rateOfCounts32.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
rateOfCounts32.CounterName = "RateOfCountsPerSecond32Sample";
CCDC.Add(rateOfCounts32);
// Create the category.
PerformanceCounterCategory.Create("RateOfCountsPerSecond32SampleCategory",
"Demonstrates usage of the RateOfCountsPerSecond32 performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC);
return (true);
}
else
{
Console.WriteLine("Category exists - RateOfCountsPerSecond32SampleCategory");
return (false);
}
}
private static void CreateCounters()
{
// Create the counter.
PC = new PerformanceCounter("RateOfCountsPerSecond32SampleCategory",
"RateOfCountsPerSecond32Sample",
false);
PC.RawValue = 0;
}
private static void CollectSamples(ArrayList samplesList)
{
Random r = new Random(DateTime.Now.Millisecond);
// Initialize the performance counter.
PC.NextSample();
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
int value = r.Next(1, 10);
PC.IncrementBy(value);
Console.Write(j + " = " + value);
if ((j % 10) == 9)
{
Console.WriteLine("; NextValue() = " + PC.NextValue().ToString());
OutputSample(PC.NextSample());
samplesList.Add(PC.NextSample());
}
else
{
Console.WriteLine();
}
System.Threading.Thread.Sleep(50);
}
}
private static void CalculateResults(ArrayList samplesList)
{
for (int i = 0; i < (samplesList.Count - 1); i++)
{
// Output the sample.
OutputSample((CounterSample)samplesList[i]);
OutputSample((CounterSample)samplesList[i + 1]);
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
// PERF_COUNTER_COUNTER
// Description - This counter type shows the average number of operations completed
// during each second of the sample interval. Counters of this type
// measure time in ticks of the system clock. The F variable represents
// the number of ticks per second. The value of F is factored into the
// equation so that the result can be displayed in seconds.
//
// Generic type - Difference
//
// Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
// of operations performed during the last sample interval, the denominator
// (D) represents the number of ticks elapsed during the last sample
// interval, and F is the frequency of the ticks.
//
// Average - (Nx - N0) / ((Dx - D0) / F)
//
// Example - System\ File Read Operations/sec
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
{
Single numerator = (Single)(s1.RawValue - s0.RawValue);
Single denomenator = (Single)(s1.TimeStamp - s0.TimeStamp) / (Single)s1.SystemFrequency;
Single counterValue = numerator / denomenator;
return (counterValue);
}
// Output information about the counter sample.
private static void OutputSample(CounterSample s)
{
Console.WriteLine("\r\n+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.Versioning
<SupportedOSPlatform("Windows")>
Public Class App4
Private Shared PC As PerformanceCounter
Public Shared Sub Main()
Dim samplesList As New ArrayList()
'If the category does not exist, create the category and exit.
'Performance counters should not be created and immediately used.
'There is a latency time to enable the counters, they should be created
'prior to executing the App4lication that uses the counters.
'Execute this sample a second time to use the counters.
If Not (SetupCategory()) Then
CreateCounters()
CollectSamples(samplesList)
CalculateResults(samplesList)
End If
End Sub
Private Shared Function SetupCategory() As Boolean
If Not PerformanceCounterCategory.Exists("RateOfCountsPerSecond32SampleCategory") Then
Dim CCDC As New CounterCreationDataCollection()
' Add the counter.
Dim rateOfCounts32 As New CounterCreationData()
rateOfCounts32.CounterType = PerformanceCounterType.RateOfCountsPerSecond32
rateOfCounts32.CounterName = "RateOfCountsPerSecond32Sample"
CCDC.Add(rateOfCounts32)
' Create the category.
PerformanceCounterCategory.Create("RateOfCountsPerSecond32SampleCategory", _
"Demonstrates usage of the RateOfCountsPerSecond32 performance counter type.", _
PerformanceCounterCategoryType.SingleInstance, CCDC)
Return True
Else
Console.WriteLine("Category exists - RateOfCountsPerSecond32SampleCategory")
Return False
End If
End Function 'SetupCategory
Private Shared Sub CreateCounters()
' Create the counter.
PC = New PerformanceCounter("RateOfCountsPerSecond32SampleCategory", "RateOfCountsPerSecond32Sample", False)
PC.RawValue = 0
End Sub
Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)
Dim r As New Random(DateTime.Now.Millisecond)
' Initialize the performance counter.
PC.NextSample()
' Loop for the samples.
Dim j As Integer
For j = 0 To 99
Dim value As Integer = r.Next(1, 10)
PC.IncrementBy(value)
Console.Write((j.ToString() + " = " + value.ToString()))
If j Mod 10 = 9 Then
Console.WriteLine(("; NextValue() = " + PC.NextValue().ToString()))
OutputSample(PC.NextSample())
samplesList.Add(PC.NextSample())
Else
Console.WriteLine()
End If
System.Threading.Thread.Sleep(50)
Next j
End Sub
Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
Dim i As Integer
For i = 0 To (samplesList.Count - 1) - 1
' Output the sample.
OutputSample(CType(samplesList(i), CounterSample))
OutputSample(CType(samplesList((i + 1)), CounterSample))
' Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
' Calculate the counter value manually.
Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
Next i
End Sub
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
' PERF_COUNTER_COUNTER
' Description - This counter type shows the average number of operations completed
' during each second of the sample interval. Counters of this type
' measure time in ticks of the system clock. The F variable represents
' the number of ticks per second. The value of F is factored into the
' equation so that the result can be displayed in seconds.
'
' Generic type - Difference
'
' Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
' of operations performed during the last sample interval, the denominator
' (D) represents the number of ticks elapsed during the last sample
' interval, and F is the frequency of the ticks.
'
' Average - (Nx - N0) / ((Dx - D0) / F)
'
' Example - System\ File Read Operations/sec
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
Private Shared Function MyComputeCounterValue(ByVal s0 As CounterSample, ByVal s1 As CounterSample) As [Single]
Dim numerator As [Single] = CType(s1.RawValue - s0.RawValue, [Single])
Dim denomenator As [Single] = CType(s1.TimeStamp - s0.TimeStamp, [Single]) / CType(s1.SystemFrequency, [Single])
Dim counterValue As [Single] = numerator / denomenator
Return counterValue
End Function 'MyComputeCounterValue
' Output information about the counter sample.
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
Console.WriteLine((" BaseValue = " + s.BaseValue.ToString()))
Console.WriteLine((" CounterFrequency = " + s.CounterFrequency.ToString()))
Console.WriteLine((" CounterTimeStamp = " + s.CounterTimeStamp.ToString()))
Console.WriteLine((" CounterType = " + s.CounterType.ToString()))
Console.WriteLine((" RawValue = " + s.RawValue.ToString()))
Console.WriteLine((" SystemFrequency = " + s.SystemFrequency.ToString()))
Console.WriteLine((" TimeStamp = " + s.TimeStamp.ToString()))
Console.WriteLine((" TimeStamp100nSec = " + s.TimeStamp100nSec.ToString()))
Console.WriteLine("++++++++++++++++++++++")
End Sub
End Class
RateOfCountsPerSecond64
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Versioning;
[SupportedOSPlatform("Windows")]
public class App4
{
private static PerformanceCounter PC;
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Perfomance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if (!PerformanceCounterCategory.Exists("RateOfCountsPerSecond64SampleCategory"))
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData rateOfCounts64 = new CounterCreationData();
rateOfCounts64.CounterType = PerformanceCounterType.RateOfCountsPerSecond64;
rateOfCounts64.CounterName = "RateOfCountsPerSecond64Sample";
CCDC.Add(rateOfCounts64);
// Create the category.
PerformanceCounterCategory.Create("RateOfCountsPerSecond64SampleCategory",
"Demonstrates usage of the RateOfCountsPerSecond64 performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC);
return (true);
}
else
{
Console.WriteLine("Category exists - RateOfCountsPerSecond64SampleCategory");
return (false);
}
}
private static void CreateCounters()
{
// Create the counter.
PC = new PerformanceCounter("RateOfCountsPerSecond64SampleCategory",
"RateOfCountsPerSecond64Sample",
false);
PC.RawValue = 0;
}
private static void CollectSamples(ArrayList samplesList)
{
Random r = new Random(DateTime.Now.Millisecond);
// Initialize the performance counter.
PC.NextSample();
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
int value = r.Next(1, 10);
PC.IncrementBy(value);
Console.Write(j + " = " + value);
if ((j % 10) == 9)
{
Console.WriteLine("; NextValue() = " + PC.NextValue().ToString());
OutputSample(PC.NextSample());
samplesList.Add(PC.NextSample());
}
else
{
Console.WriteLine();
}
System.Threading.Thread.Sleep(50);
}
}
private static void CalculateResults(ArrayList samplesList)
{
for (int i = 0; i < (samplesList.Count - 1); i++)
{
// Output the sample.
OutputSample((CounterSample)samplesList[i]);
OutputSample((CounterSample)samplesList[i + 1]);
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i],
(CounterSample)samplesList[i + 1]));
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
// PERF_COUNTER_COUNTER
// Description - This counter type shows the average number of operations completed
// during each second of the sample interval. Counters of this type
// measure time in ticks of the system clock. The F variable represents
// the number of ticks per second. The value of F is factored into the
// equation so that the result can be displayed in seconds.
//
// Generic type - Difference
//
// Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
// of operations performed during the last sample interval, the denominator
// (D) represents the number of ticks elapsed during the last sample
// interval, and F is the frequency of the ticks.
//
// Average - (Nx - N0) / ((Dx - D0) / F)
//
// Example - System\ File Read Operations/sec
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
{
Single numerator = (Single)(s1.RawValue - s0.RawValue);
Single denomenator = (Single)(s1.TimeStamp - s0.TimeStamp) / (Single)s1.SystemFrequency;
Single counterValue = numerator / denomenator;
return (counterValue);
}
private static void OutputSample(CounterSample s)
{
Console.WriteLine("\r\n+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.Versioning
<SupportedOSPlatform("Windows")>
Public Class App5
Private Shared PC As PerformanceCounter
Public Shared Sub Main()
Dim samplesList As New ArrayList()
'If the category does not exist, create the category and exit.
'Performance counters should not be created and immediately used.
'There is a latency time to enable the counters, they should be created
'prior to executing the App5lication that uses the counters.
'Execute this sample a second time to use the counters.
If Not (SetupCategory()) Then
CreateCounters()
CollectSamples(samplesList)
CalculateResults(samplesList)
End If
End Sub
Private Shared Function SetupCategory() As Boolean
If Not PerformanceCounterCategory.Exists("RateOfCountsPerSecond64SampleCategory") Then
Dim CCDC As New CounterCreationDataCollection()
' Add the counter.
Dim rateOfCounts64 As New CounterCreationData()
rateOfCounts64.CounterType = PerformanceCounterType.RateOfCountsPerSecond64
rateOfCounts64.CounterName = "RateOfCountsPerSecond64Sample"
CCDC.Add(rateOfCounts64)
' Create the category.
PerformanceCounterCategory.Create("RateOfCountsPerSecond64SampleCategory", _
"Demonstrates usage of the RateOfCountsPerSecond64 performance counter type.", _
PerformanceCounterCategoryType.SingleInstance, CCDC)
Return True
Else
Console.WriteLine("Category exists - RateOfCountsPerSecond64SampleCategory")
Return False
End If
End Function 'SetupCategory
Private Shared Sub CreateCounters()
' Create the counter.
PC = New PerformanceCounter("RateOfCountsPerSecond64SampleCategory", "RateOfCountsPerSecond64Sample", False)
PC.RawValue = 0
End Sub
Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)
Dim r As New Random(DateTime.Now.Millisecond)
' Initialize the performance counter.
PC.NextSample()
' Loop for the samples.
Dim j As Integer
For j = 0 To 99
Dim value As Integer = r.Next(1, 10)
PC.IncrementBy(value)
Console.Write((j.ToString() + " = " + value.ToString()))
If j Mod 10 = 9 Then
Console.WriteLine(("; NextValue() = " + PC.NextValue().ToString()))
OutputSample(PC.NextSample())
samplesList.Add(PC.NextSample())
Else
Console.WriteLine()
End If
System.Threading.Thread.Sleep(50)
Next j
End Sub
Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
Dim i As Integer
For i = 0 To (samplesList.Count - 1) - 1
' Output the sample.
OutputSample(CType(samplesList(i), CounterSample))
OutputSample(CType(samplesList((i + 1)), CounterSample))
' Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " + _
CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
' Calculate the counter value manually.
Console.WriteLine("My computed counter value = " + _
MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
Next i
End Sub
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
' PERF_COUNTER_COUNTER
' Description - This counter type shows the average number of operations completed
' during each second of the sample interval. Counters of this type
' measure time in ticks of the system clock. The F variable represents
' the number of ticks per second. The value of F is factored into the
' equation so that the result can be displayed in seconds.
'
' Generic type - Difference
'
' Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
' of operations performed during the last sample interval, the denominator
' (D) represents the number of ticks elapsed during the last sample
' interval, and F is the frequency of the ticks.
'
' Average - (Nx - N0) / ((Dx - D0) / F)
'
' Example - System\ File Read Operations/sec
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
Private Shared Function MyComputeCounterValue(ByVal s0 As CounterSample, ByVal s1 As CounterSample) As [Single]
Dim numerator As [Single] = CType(s1.RawValue - s0.RawValue, [Single])
Dim denomenator As [Single] = CType(s1.TimeStamp - s0.TimeStamp, [Single]) / CType(s1.SystemFrequency, [Single])
Dim counterValue As [Single] = numerator / denomenator
Return counterValue
End Function 'MyComputeCounterValue
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
Console.WriteLine((" BaseValue = " + s.BaseValue.ToString()))
Console.WriteLine((" CounterFrequency = " + s.CounterFrequency.ToString()))
Console.WriteLine((" CounterTimeStamp = " + s.CounterTimeStamp.ToString()))
Console.WriteLine((" CounterType = " + s.CounterType.ToString()))
Console.WriteLine((" RawValue = " + s.RawValue.ToString()))
Console.WriteLine((" SystemFrequency = " + s.SystemFrequency.ToString()))
Console.WriteLine((" TimeStamp = " + s.TimeStamp.ToString()))
Console.WriteLine((" TimeStamp100nSec = " + s.TimeStamp100nSec.ToString()))
Console.WriteLine("++++++++++++++++++++++")
End Sub
End Class
RawFraction
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Versioning;
[SupportedOSPlatform("Windows")]
public class App5
{
private static PerformanceCounter PC;
private static PerformanceCounter BPC;
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the counters.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if (!PerformanceCounterCategory.Exists("RawFractionSampleCategory"))
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData rf = new CounterCreationData();
rf.CounterType = PerformanceCounterType.RawFraction;
rf.CounterName = "RawFractionSample";
CCDC.Add(rf);
// Add the base counter.
CounterCreationData rfBase = new CounterCreationData();
rfBase.CounterType = PerformanceCounterType.RawBase;
rfBase.CounterName = "RawFractionSampleBase";
CCDC.Add(rfBase);
// Create the category.
PerformanceCounterCategory.Create("RawFractionSampleCategory",
"Demonstrates usage of the RawFraction performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC);
return (true);
}
else
{
Console.WriteLine("Category exists - RawFractionSampleCategory");
return (false);
}
}
private static void CreateCounters()
{
// Create the counters.
PC = new PerformanceCounter("RawFractionSampleCategory",
"RawFractionSample",
false);
BPC = new PerformanceCounter("RawFractionSampleCategory",
"RawFractionSampleBase",
false);
PC.RawValue = 0;
BPC.RawValue = 0;
}
private static void CollectSamples(ArrayList samplesList)
{
Random r = new Random(DateTime.Now.Millisecond);
// Initialize the performance counter.
PC.NextSample();
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
int value = r.Next(1, 10);
Console.Write(j + " = " + value);
// Increment the base every time, because the counter measures the number
// of high hits (raw fraction value) against all the hits (base value).
BPC.Increment();
// Get the % of samples that are 9 or 10 out of all the samples taken.
if (value >= 9)
PC.Increment();
// Copy out the next value every ten times around the loop.
if ((j % 10) == 9)
{
Console.WriteLine("; NextValue() = " + PC.NextValue().ToString());
OutputSample(PC.NextSample());
samplesList.Add(PC.NextSample());
}
else
{
Console.WriteLine();
}
System.Threading.Thread.Sleep(50);
}
}
private static void CalculateResults(ArrayList samplesList)
{
for (int i = 0; i < samplesList.Count; i++)
{
// Output the sample.
OutputSample((CounterSample)samplesList[i]);
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i]));
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i]));
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
// Formula from MSDN -
// Description - This counter type shows the ratio of a subset to its set as a percentage.
// For example, it compares the number of bytes in use on a disk to the
// total number of bytes on the disk. Counters of this type display the
// current percentage only, not an average over time.
//
// Generic type - Instantaneous, Percentage
// Formula - (N0 / D0), where D represents a measured attribute and N represents one
// component of that attribute.
//
// Average - SUM (N / D) /x
// Example - Paging File\% Usage Peak
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
private static Single MyComputeCounterValue(CounterSample rfSample)
{
Single numerator = (Single)rfSample.RawValue;
Single denomenator = (Single)rfSample.BaseValue;
Single counterValue = (numerator / denomenator) * 100;
return (counterValue);
}
// Output information about the counter sample.
private static void OutputSample(CounterSample s)
{
Console.WriteLine("+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.Versioning
<SupportedOSPlatform("Windows")>
Public Class App6
Private Shared PC As PerformanceCounter
Private Shared BPC As PerformanceCounter
Public Shared Sub Main()
Dim samplesList As New ArrayList()
'If the category does not exist, create the category and exit.
'Performance counters should not be created and immediately used.
'There is a latency time to enable the counters, they should be created
'prior to executing the App6lication that uses the counters.
'Execute this sample a second time to use the counters.
If Not (SetupCategory()) Then
CreateCounters()
CollectSamples(samplesList)
CalculateResults(samplesList)
End If
End Sub
Private Shared Function SetupCategory() As Boolean
If Not PerformanceCounterCategory.Exists("RawFractionSampleCategory") Then
Dim CCDC As New CounterCreationDataCollection()
' Add the counter.
Dim rf As New CounterCreationData()
rf.CounterType = PerformanceCounterType.RawFraction
rf.CounterName = "RawFractionSample"
CCDC.Add(rf)
' Add the base counter.
Dim rfBase As New CounterCreationData()
rfBase.CounterType = PerformanceCounterType.RawBase
rfBase.CounterName = "RawFractionSampleBase"
CCDC.Add(rfBase)
' Create the category.
PerformanceCounterCategory.Create("RawFractionSampleCategory",
"Demonstrates usage of the RawFraction performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC)
Return True
Else
Console.WriteLine("Category exists - RawFractionSampleCategory")
Return False
End If
End Function 'SetupCategory
Private Shared Sub CreateCounters()
' Create the counters.
PC = New PerformanceCounter("RawFractionSampleCategory", "RawFractionSample", False)
BPC = New PerformanceCounter("RawFractionSampleCategory", "RawFractionSampleBase", False)
PC.RawValue = 0
BPC.RawValue = 0
End Sub
Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)
Dim r As New Random(DateTime.Now.Millisecond)
' Initialize the performance counter.
PC.NextSample()
' Loop for the samples.
Dim j As Integer
For j = 0 To 99
Dim value As Integer = r.Next(1, 10)
Console.Write((j.ToString() + " = " + value.ToString()))
' Increment the base every time, because the counter measures the number
' of high hits (raw fraction value) against all the hits (base value).
BPC.Increment()
' Get the % of samples that are 9 or 10 out of all the samples taken.
If value >= 9 Then
PC.Increment()
End If
' Copy out the next value every ten times around the loop.
If j Mod 10 = 9 Then
Console.WriteLine(("; NextValue() = " + PC.NextValue().ToString()))
OutputSample(PC.NextSample())
samplesList.Add(PC.NextSample())
Else
Console.WriteLine()
End If
System.Threading.Thread.Sleep(50)
Next j
End Sub
Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
Dim i As Integer
For i = 0 To samplesList.Count - 1
' Output the sample.
OutputSample(CType(samplesList(i), CounterSample))
' Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample)).ToString())
' Calculate the counter value manually.
Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample)).ToString())
Next i
End Sub
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
' Formula from MSDN -
' Description - This counter type shows the ratio of a subset to its set as a percentage.
' For example, it compares the number of bytes in use on a disk to the
' total number of bytes on the disk. Counters of this type display the
' current percentage only, not an average over time.
'
' Generic type - Instantaneous, Percentage
' Formula - (N0 / D0), where D represents a measured attribute and N represents one
' component of that attribute.
'
' Average - SUM (N / D) /x
' Example - Paging File\% Usage Peak
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
Private Shared Function MyComputeCounterValue(ByVal rfSample As CounterSample) As [Single]
Dim numerator As [Single] = CType(rfSample.RawValue, [Single])
Dim denomenator As [Single] = CType(rfSample.BaseValue, [Single])
Dim counterValue As [Single] = numerator / denomenator * 100
Return counterValue
End Function 'MyComputeCounterValue
' Output information about the counter sample.
Private Shared Sub OutputSample(ByVal s As CounterSample)
Console.WriteLine("+++++++++++")
Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
Console.WriteLine((" BaseValue = " + s.BaseValue.ToString()))
Console.WriteLine((" CounterFrequency = " + s.CounterFrequency.ToString()))
Console.WriteLine((" CounterTimeStamp = " + s.CounterTimeStamp.ToString()))
Console.WriteLine((" CounterType = " + s.CounterType.ToString()))
Console.WriteLine((" RawValue = " + s.RawValue.ToString()))
Console.WriteLine((" SystemFrequency = " + s.SystemFrequency.ToString()))
Console.WriteLine((" TimeStamp = " + s.TimeStamp.ToString()))
Console.WriteLine((" TimeStamp100nSec = " + s.TimeStamp100nSec.ToString()))
Console.WriteLine("++++++++++++++++++++++")
End Sub
End Class