|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionAlthough the .NET Framework provides usage of performance counters under the I started to dig into CodeProject and some newsgroups, and found many articles covering the same problem. After I found the solution, I started to write an article, which introduces using performance counters in .NET and especially how to use I am sorry, that I only have German Windows editions, so the images contained in the article contain German names for buttons, etc. I tried to find the correct translation to English, but I am not quite sure if they are accurate. Maybe somebody can help me out with images of English versions, so that I can provide them here. Getting startedPerformance counters can monitor system components such as processors, memory, and network I/O. If you use performance counters in your application, they can publish performance-related data to compare them against acceptable criteria. Performance counters are available on Microsoft operating systems Windows 2000 and later. Performance counters can be made visible using the Performance monitor (perfmon.exe). Later, I will show how to add and remove performance counters in the Performance monitor. Performance Counter TypesDifferent performance counter types are available, covering different performance interests. They range from counts to those which calculate averages. Some of the performance counter types are for special situations only, but the following list contains the most common types you will normally use - and this article is covering:
You will find the performance counter types in the Categories, Counters And InstancesPerformance counters are combined together under categories, such as Processor or Memory. A category catalogues performance counters in a logical unit. A performance counter itself can be divided into instances, such as processes, threads, or physical units. ExampleWhen monitoring the processor load a process takes while execution, you will find the performance counter % Processor time in the category Processor. Underneath that counter, you will find an instance for each process currently running on your system. Creation And Setup Of Performance CountersThere are two ways to create performance counters. You can either create them using the Server-Explorer or create them programmatically by code. Creating performance counters using the Server-Explorer is much easier than doing it by code, but on production machines, you might not be able to install Visual Studio .NET to take advantage of this feature. However, I will explain both ways. Creating Performance Counters Using Server-ExplorerThe simplest way to set up performance categories and counters is by using Server-Explorer integrated within Visual Studio .NET. Normally, you will find it at left side toolbar where you also have your Toolbox for designing Windows Forms. If you don't see it, you might have closed it before. Then, direct to the "View" menu and select the "Server-Explorer" option. Setting up new categories is pretty easy. Open the "Server-Explorer" and open the tree-node "Performance counters". The tree should open and you should see all performance categories currently available on your system (Figure 1).
Figure 1 Now right-click on "Performance counters" and select "Add new category" to add a new category. Enter a name, a description, and some counters to it, and you're done. You can also right-click on a category and select "Show category" to add some more counters to any existing category (Figure 2).
Figure 2 Performance Counter Installation By CodePerformance counters can be created manually at runtime by code. It takes much more effort to do so, but once you learn how, it is as simple as doing so by Server-Explorer. When creating performance counters and/or categories by code, you must take care, that the user running the code must have the proper administrative rights. This might be a problem when using performance counters in Web Applications because the ASP.NET user does not have them. Installing performance counters programmatically includes using some classes from the
To create a new performance category which comes along with some counts, you will first create a Let's look at some code: if (!PerformanceCounterCategory.Exists("MyCategory"))
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
// 1. counter for counting totals: PerformanceCounterType.NumberOfItems32
CounterCreationData totalOps = new CounterCreationData();
totalOps.CounterName = "# operations executed";
totalOps.CounterHelp = "Total number of operations executed";
totalOps.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(totalOps);
// 2. counter for counting operations per second:
// PerformanceCounterType.RateOfCountsPerSecond32
CounterCreationData opsPerSecond = new CounterCreationData();
opsPerSecond.CounterName = "# operations / sec";
opsPerSecond.CounterHelp = "Number of operations executed per second";
opsPerSecond.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
counters.Add(opsPerSecond);
// 3. counter for counting average time per operation:
// PerformanceCounterType.AverageTimer32
CounterCreationData avgDuration = new CounterCreationData();
avgDuration.CounterName = "average time per operation";
avgDuration.CounterHelp = "Average duration per operation execution";
avgDuration.CounterType = PerformanceCounterType.AverageTimer32;
counters.Add(avgDuration);
// 4. base counter for counting average time
// per operation: PerformanceCounterType.AverageBase
CounterCreationData avgDurationBase = new CounterCreationData();
avgDurationBase.CounterName = "average time per operation base";
avgDurationBase.CounterHelp = "Average duration per operation execution base";
avgDurationBase.CounterType = PerformanceCounterType.AverageBase;
counters.Add(avgDurationBase);
// create new category with the counters above
PerformanceCounterCategory.Create("MyCategory",
"Sample category for Codeproject", counters);
}
Executing the code above creates a new performance category called "MyCategory" and adds some performance counters to it ("# operations executed", "# operations / sec", "average time per operation"). But you won't be able to change values of the counters yet. Open Server-Explorer and switch to "Performance counters". You will find the new category there and also the three new counters under that category. Maybe, you'll have to refresh the view by right-clicking "Performance counters" and selecting refresh to make the changes visible (Figure 3).
Figure 3 As I told before, creating counters which require some calculation requires a supporting base counter. The example above added only three counters to the category, but four To create a new category and add some performance counters to it, you must:
Remember, you won't be able to create categories and/or counters that already exist! Working With Performance CountersAfter installing performance counters, you usually want to use them to monitor performance. Therefore, you can use the Create Performance Counters To Work WithCreating performance counters to work with is easy. Create a new instance of
You can leave the other properties at its defaults as we don't require them to change now. // create counters to work with
_TotalOperations = new PerformanceCounter();
_TotalOperations.CategoryName = "MyCategory";
_TotalOperations.CounterName = "# operations executed";
_TotalOperations.MachineName = ".";
_TotalOperations.ReadOnly = false;
_OperationsPerSecond = new PerformanceCounter();
_OperationsPerSecond.CategoryName = "MyCategory";
_OperationsPerSecond.CounterName = "# operations / sec";
_OperationsPerSecond.MachineName = ".";
_OperationsPerSecond.ReadOnly = false;
_AverageDuration = new PerformanceCounter();
_AverageDuration.CategoryName = "MyCategory";
_AverageDuration.CounterName = "average time per operation";
_AverageDuration.MachineName = ".";
_AverageDuration.ReadOnly = false;
_AverageDurationBase = new PerformanceCounter();
_AverageDurationBase.CategoryName = "MyCategory";
_AverageDurationBase.CounterName = "average time per operation base";
_AverageDurationBase.MachineName = ".";
_AverageDurationBase.ReadOnly = false;
Changing performance Counter ValuesMonitoring performance means changing performance values after a certain amount of time. To do so, we can call one of the following methods on a
// simply increment the counters
_TotalOperations.Increment();
_OperationsPerSecond.Increment();
// increment the timer by the time cost of the operation
_AverageDuration.IncrementBy(ticks);
// increment base counter only by 1
_AverageDurationBase.Increment();
Using AverageTimer32 And AverageBaseIn the sample code above, you can see how we must increment the counters for calculating averages. While the counter of type The .NET documentation for We should expect that we could use [DllImport("Kernel32.dll")]
public static extern void QueryPerformanceCounter(ref long ticks);
// [...]
PerformanceCounterSample test = new PerformanceCounterSample();
Random rand = new Random();
long startTime = 0;
long endTime = 0;
for (int i=0; i<1000; i++)
{
// measure starting time
QueryPerformanceCounter(ref startTime);
System.Threading.Thread.Sleep(rand.Next(500));
// measure ending time
QueryPerformanceCounter(ref endTime);
// do some processing
test.DoSomeProcessing(endTime - startTime);
}
Making Performance VisibleMost of you already know how to set up Performance Monitor to make performance counters visible. But for all those who don't know it yet, I will explain it in just a few words. You find Performance Monitor under Administrative Tools in the Control panel. Double-click it and a window will show up with a Y-Axis ranging from 0 to 100 and a imaginary X-Axis, which depicts the time elapsed. You can add counters using the If your machine is running with a single-processor, switch the category to Process and see the listbox containing the counters changing. Again processor time should be pre-selected, but now you should see instances for each process currently running. Select the Idle process and click Add, and then close the window. Now you can see that the performance monitor starts recording performance. Move your mouse a little to take processor time from the idle process, and you should see that the curve drawn moves down when you move your mouse, and again goes up to 100 when you keep quiet (if you don't have other time consuming processes running).
Figure 4 For some reasons, you might have to change the scale of the counter. To do so, right-click anywhere in performance monitor and select Properties and then Data. Select the counter of which you require to change the scale, and change the factor with the dropdown listbox, and click OK. You can also change the color and thickness of the curve drawn for that counter here. Play with the performance monitor a little to understand how you can monitor performance using it. Putting It All TogetherThe following sample sets up a new category "MyCategory" and adds some performance counters to it ("# operations executed", "# operations / sec", "average time per operation"). It simulates processing by calling the method
|
||||||||||||||||||||||