Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Classe PerformanceCounter

 

Representa um componente do contador de desempenho do Windows NT.

Namespace:   System.Diagnostics
Assembly:  System (em System.dll)

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Diagnostics.PerformanceCounter

[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	SharedState = true)]
public sealed class PerformanceCounter : Component, ISupportInitialize

NomeDescrição
System_CAPS_pubmethodPerformanceCounter()

Inicializa uma nova instância somente leitura da classe PerformanceCounter, sem associar a instância a nenhum sistema ou contador de desempenho personalizado.

System_CAPS_pubmethodPerformanceCounter(String, String)

Inicializa uma instância nova e somente leitura da classe PerformanceCounter e a associa ao contador de desempenho personalizado ou do sistema, especificado no computador local. Este construtor requer que a categoria de tenha uma única instância.

System_CAPS_pubmethodPerformanceCounter(String, String, Boolean)

Inicializa uma instância nova e somente leitura ou de leitura/gravação da classe PerformanceCounter e a associa ao contador de desempenho personalizado ou do sistema especificado no computador local. Este construtor requer que a categoria contenha uma única instância.

System_CAPS_pubmethodPerformanceCounter(String, String, String)

Inicializa uma instância nova e somente leitura da classe PerformanceCounter e a associa ao sistema especificado ou ao contador de desempenho personalizado e à instância de categoria no computador local.

System_CAPS_pubmethodPerformanceCounter(String, String, String, Boolean)

Inicializa uma instância nova e somente leitura ou de leitura/gravação da classe PerformanceCounter e a associa ao sistema especificado ou ao contador de desempenho personalizado e à instância de categoria no computador local.

System_CAPS_pubmethodPerformanceCounter(String, String, String, String)

Inicializa uma instância nova e somente leitura da classe PerformanceCounter e a associa ao sistema especificado ou ao contador de desempenho personalizado e à instância de categoria no computador especificado.

NomeDescrição
System_CAPS_pubpropertyCategoryName

Obtém ou define o nome da categoria do contador de desempenho desse contador de desempenho.

System_CAPS_pubpropertyContainer

Obtém o IContainer que contém o Component.(Herdado de Component.)

System_CAPS_pubpropertyCounterHelp

Obtém a descrição para este contador de desempenho.

System_CAPS_pubpropertyCounterName

Obtém ou define o nome do contador de desempenho associado a esta instância PerformanceCounter.

System_CAPS_pubpropertyCounterType

Obtém o tipo do contador de desempenho associado.

System_CAPS_pubpropertyInstanceLifetime

Obtém ou define o tempo de vida de um processo.

System_CAPS_pubpropertyInstanceName

Obtém ou define um nome de instância para o contador de desempenho.

System_CAPS_pubpropertyMachineName

Obtém ou define um nome do computador para esse contador de desempenho

System_CAPS_pubpropertyRawValue

Obtém ou define o valor bruto, ou não calculado, desse contador.

System_CAPS_pubpropertyReadOnly

Obtém ou define um valor que indica se este PerformanceCounter instância está no modo somente leitura.

System_CAPS_pubpropertySite

Obtém ou define o ISite do Component.(Herdado de Component.)

NomeDescrição
System_CAPS_pubmethodBeginInit()

Começa a inicialização de um PerformanceCounter instância usada em um formulário ou por outro componente. A inicialização ocorre em tempo de execução.

System_CAPS_pubmethodClose()

O contador de desempenho de fecha e libera todos os recursos alocados por essa instância do contador de desempenho.

System_CAPS_pubmethodSystem_CAPS_staticCloseSharedResources()

Libera o estado de biblioteca compartilhada do contador de desempenho alocado pelos contadores.

System_CAPS_pubmethodCreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.(Herdado de MarshalByRefObject.)

System_CAPS_pubmethodDecrement()

Diminui o contador de desempenho associados por uma por meio de uma operação atômica eficiente.

System_CAPS_pubmethodDispose()

Libera todos os recursos usados pelo Component.(Herdado de Component.)

System_CAPS_pubmethodEndInit()

Termina a inicialização de um PerformanceCounter instância é usada em um formulário ou por outro componente. A inicialização ocorre em tempo de execução.

System_CAPS_pubmethodEquals(Object)

Determina se o objeto especificado é igual ao objeto atual.(Herdado de Object.)

System_CAPS_pubmethodGetHashCode()

Serve como a função de hash padrão.(Herdado de Object.)

System_CAPS_pubmethodGetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.(Herdado de MarshalByRefObject.)

System_CAPS_pubmethodGetType()

Obtém o Type da instância atual.(Herdado de Object.)

System_CAPS_pubmethodIncrement()

Incrementa em um o contador de desempenho associado através de uma operação atômica eficiente.

System_CAPS_pubmethodIncrementBy(Int64)

Incrementa ou diminui o valor do contador de desempenho associado em um valor especificado por meio de uma operação atômica eficiente.

System_CAPS_pubmethodInitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.(Herdado de MarshalByRefObject.)

System_CAPS_pubmethodNextSample()

Obtém uma amostra de contador e retorna o valor bruto ou não calculado para ela.

System_CAPS_pubmethodNextValue()

Obtém uma amostra de contador e retorna o valor calculado para ela.

System_CAPS_pubmethodRemoveInstance()

Exclui a instância da categoria especificada pelo PerformanceCounter objeto InstanceName propriedade.

System_CAPS_pubmethodToString()

Retorna um String que contém o nome do Component, se houver. Esse método não deve ser substituído.(Herdado de Component.)

NomeDescrição
System_CAPS_pubfieldSystem_CAPS_staticDefaultFileMappingSize

Obsoleto. Especifica o tamanho, em bytes, da memória global compartilhado por contadores de desempenho. O tamanho padrão é 524.288 bytes.

NomeDescrição
System_CAPS_pubeventDisposed

Ocorre quando o componente é disposto por uma chamada para o método Dispose.(Herdado de Component.)

The T:System.Diagnostics.PerformanceCounter component can be used for both reading existing predefined or custom counters and publishing (writing) performance data to custom counters.

There are numerous predefined counters listed in the Windows Performance Monitor's Add Counters dialog boxhttp://go.microsoft.com/fwlink/p/?LinkId=257854. To learn about the .NET Framework performance counters, see Performance Counters in the .NET Framework.

This type implements the T:System.IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its M:System.IDisposable.Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the T:System.IDisposable interface topic.

System_CAPS_importantImportante

In versions 1.0 and 1.1 of the .NET Framework, this class requires immediate callers to be fully trusted. Starting with the .NET Framework version 2.0, this class requires T:System.Diagnostics.PerformanceCounterPermission for specific actions. It is strongly recommended that T:System.Diagnostics.PerformanceCounterPermission not be granted to semi-trusted code. The ability to read and write performance counters allows code to perform actions such as enumerating executing processes and obtaining information about them.

In addition, passing a T:System.Diagnostics.PerformanceCounter object to less-trusted code can create a security issue. Never pass performance counter objects, such as a T:System.Diagnostics.PerformanceCounterCategory or T:System.Diagnostics.PerformanceCounter, to less trusted code.

To read from a performance counter, create an instance of the T:System.Diagnostics.PerformanceCounter class, set the P:System.Diagnostics.PerformanceCounter.CategoryName, P:System.Diagnostics.PerformanceCounter.CounterName, and, optionally, the P:System.Diagnostics.PerformanceCounter.InstanceName or P:System.Diagnostics.PerformanceCounter.MachineName properties, and then call the M:System.Diagnostics.PerformanceCounter.NextValue method to take a performance counter reading.

To publish performance counter data, create one or more custom counters using the M:System.Diagnostics.PerformanceCounterCategory.Create(System.String,System.String,System.Diagnostics.CounterCreationDataCollection) method, create an instance of the T:System.Diagnostics.PerformanceCounter class, set the P:System.Diagnostics.PerformanceCounter.CategoryName, P:System.Diagnostics.PerformanceCounter.CounterName and, optionally, P:System.Diagnostics.PerformanceCounter.InstanceName or P:System.Diagnostics.PerformanceCounter.MachineName properties, and then call the M:System.Diagnostics.PerformanceCounter.IncrementBy(System.Int64), M:System.Diagnostics.PerformanceCounter.Increment, or M:System.Diagnostics.PerformanceCounter.Decrement methods, or set the P:System.Diagnostics.PerformanceCounter.RawValue property to change the value of your custom counter.

System_CAPS_noteObservação

The M:System.Diagnostics.PerformanceCounter.Increment, M:System.Diagnostics.PerformanceCounter.IncrementBy(System.Int64), and M:System.Diagnostics.PerformanceCounter.Decrement methods use interlocks to update the counter value. This helps keep the counter value accurate in multithreaded or multiprocess scenarios, but also results in a performance penalty. If you do not need the accuracy that interlocked operations provide, you can update the P:System.Diagnostics.PerformanceCounter.RawValue property directly for up to a 5 times performance improvement. However, in multithreaded scenarios, some updates to the counter value might be ignored, resulting in inaccurate data.

The counter is the mechanism by which performance data is collected. The registry stores the names of all the counters, each of which is related to a specific area of system functionality. Examples include a processor's busy time, memory usage, or the number of bytes received over a network connection.

Each counter is uniquely identified through its name and its location. In the same way that a file path includes a drive, a directory, one or more subdirectories, and a file name, counter information consists of four elements: the computer, the category, the category instance, and the counter name.

The counter information must include the category, or performance object, that the counter measures data for. A computer's categories include physical components, such as processors, disks, and memory. There are also system categories, such as processes and threads. Each category is related to a functional element within the computer and has a set of standard counters assigned to it. These objects are listed in the Performance object drop-down list of the Add Counters dialog box within the Windows 2000 System Monitor, and you must include them in the counter path. Performance data is grouped by the category to which is it related.

In certain cases, several copies of the same category can exist. For example, several processes and threads run simultaneously, and some computers contain more than one processor. The category copies are called category instances, and each instance has a set of standard counters assigned to it. If a category can have more than one instance, an instance specification must be included in the counter information.

To obtain performance data for counters that required an initial or previous value for performing the necessary calculation, call the M:System.Diagnostics.PerformanceCounter.NextValue method twice and use the information returned as your application requires.

System_CAPS_noteObservação

Performance counter categories installed with the dnprdnlong use separate shared memory, with each performance counter category having its own memory. You can specify the size of separate shared memory by creating a DWORD named FileMappingSize in the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<category name>\Performance. The FileMappingSize value is set to the shared memory size of the category. The default size is 131072 decimal. If the FileMappingSize value is not present, the fileMappingSize attribute value for the performanceCounters element specified in the Machine.config file is used, causing additional overhead for configuration file processing. You can realize a performance improvement for application startup by setting the file mapping size in the registry. For more information about the file mapping size, see <performanceCounters> Element.

Win98WinMe

Performance counters are not supported on Windows 98 or Windows Millennium Edition (Me).

The following code example demonstrates the use of the T:System.Diagnostics.PerformanceCounter class to create and use an F:System.Diagnostics.PerformanceCounterType.AverageCount64 counter type. The example creates categories, sets up counters, collects data from the counters, and calls the T:System.Diagnostics.CounterSampleCalculator class to interpret the performance counter data. The intermediate and final results are displayed in the console window. For additional examples of other performance counter types, see the T:System.Diagnostics.PerformanceCounterType enumeration.


using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

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

.NET Framework
Disponível desde 1.1

Quaisquer membros estáticos públicos ( Compartilhado no Visual Basic) desse tipo são thread-safe. Não há garantia de que qualquer membro de instância seja thread-safe.

Retornar ao início
Mostrar: