public static void Main() { //<Snippet1> if (!PerformanceCounterCategory.Exists("Orders")) { CounterCreationData milk = new CounterCreationData(); milk.CounterName = "milk"; milk.CounterType = PerformanceCounterType.NumberOfItems32; CounterCreationData milkPerSecond = new CounterCreationData(); milkPerSecond.CounterName = "milk orders/second"; milkPerSecond.CounterType = PerformanceCounterType.RateOfCountsPerSecond32; CounterCreationDataCollection ccds = new CounterCreationDataCollection(); ccds.Add(milkPerSecond); ccds.Add(milk); PerformanceCounterCategory.Create("Orders", "Number of processed orders", PerformanceCounterCategoryType.SingleInstance, ccds); } //</Snippet1> }
private static CounterGroup CreateGroupPerformanceCounter(string action) { if (!PerformanceCounterCategory.Exists(CategoryName)) { return(null); } var result = new CounterGroup { Executing = new PerformanceCounter(CategoryName, CounterName_Executing, action, false), Hits = new PerformanceCounter(CategoryName, CounterName_Hits, action, false), TimeTaken = new PerformanceCounter(CategoryName, CounterName_TimeTaken, action, false), AverageDuration = new PerformanceCounter(CategoryName, CounterName_AverageDuration, action, false), AverageDurationBase = new PerformanceCounter(CategoryName, CounterName_AverageDurationBase, action, false), HitsPerSecond = new PerformanceCounter(CategoryName, CounterName_HitsPerSecond, action, false) }; result.Executing.RawValue = 0; result.Hits.RawValue = 0; result.TimeTaken.RawValue = 0; return(result); }
/// <summary> /// 检索输出本地计算机上注册的 性能计数器 类别的列表 PerformanceCounterCategory.GetCategories()。 /// </summary> public static void ToDebugPCCs() { PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories(); foreach (PerformanceCounterCategory category in categories) { if (category == null || !PerformanceCounterCategory.Exists(category.CategoryName)) { continue; } string name = "<null>"; string help = "<null>"; string machineName = "<null>"; try { name = category.CategoryName; } catch { } try { help = category.CategoryHelp; } catch { } try { machineName = category.MachineName != null ? category.MachineName : "<null>"; } catch { } Console.WriteLine("CategoryName: {0} CategoryType: {1} MachineName: {2} Help: {3}", name.PadRight(48), category.CategoryType.ToString().PadRight(16), machineName.PadRight(8), help); } }
public frmAVDevices(RegistryKey cxpclientkey) { InitializeComponent(); cxpclientRegKey = cxpclientkey; if (PerformanceCounterCategory.Exists("Processor") && PerformanceCounterCategory.CounterExists("% Processor Time", "Processor") && PerformanceCounterCategory.InstanceExists("_Total", "Processor")) { pcCPU = new PerformanceCounter("Processor", "% Processor Time", "_Total"); } if (PerformanceCounterCategory.Exists("Process") && PerformanceCounterCategory.CounterExists("Working Set", "Process") && PerformanceCounterCategory.InstanceExists( System.Reflection.Assembly.GetEntryAssembly().GetName(false).Name, "Process")) { pcMem = new PerformanceCounter("Process", "Working Set", System.Reflection.Assembly.GetEntryAssembly().GetName(false).Name); } }
internal static bool SetupCategory() { lock (PerfCounterSyncLock) { if (!PerformanceCounterCategory.Exists(CounterCategoryName)) { CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection(); // Add the counters. CounterCreationData ioRestrainCount64 = new CounterCreationData() { CounterType = PerformanceCounterType.NumberOfItems64, CounterName = IoRestrainedCounterName, CounterHelp = "指示Lagfree HDD服务正限制的进程数量" }; counterDataCollection.Add(ioRestrainCount64); CounterCreationData cpuRestrainCount64 = new CounterCreationData() { CounterType = PerformanceCounterType.NumberOfItems64, CounterName = CpuRestrainedCounterName, CounterHelp = "指示Lagfree CPU服务正限制的进程数量" }; counterDataCollection.Add(cpuRestrainCount64); // Create the category. PerformanceCounterCategory.Create(CounterCategoryName, "指示Lagfree Services工作状态的性能指标。", PerformanceCounterCategoryType.SingleInstance, counterDataCollection); return(true); } else { return(false); } } }
public static bool CheckCounters() { if (PerformanceCounterCategory.Exists(categoryName)) { bool needToRecreateCategory = false; foreach (CounterCreationData counter in Counters) { if (!PerformanceCounterCategory.CounterExists(counter.CounterName, categoryName)) { needToRecreateCategory = true; } } if (!needToRecreateCategory) { return(true); } } return(false); }
private static bool CreatePerformanceCounters() { if (!PerformanceCounterCategory.Exists("MyCategory")) { CounterCreationDataCollection counters = new CounterCreationDataCollection { new CounterCreationData( "# operations executed", "Total number of operations executed", PerformanceCounterType.NumberOfItems32), new CounterCreationData( "# operations / sec", "Number of operations executed per second", PerformanceCounterType.RateOfCountsPerSecond32) }; PerformanceCounterCategory.Create("MyCategory", "Sample category for Codeproject", counters); return(true); } return(false); }
private static CreationResult SetupPerformanceCounters() { var categoryName = "Image processing"; var counterNameImagesProcessed = "% of images processed"; var counterNameImagesPerSecond = "# images processed per second"; if (PerformanceCounterCategory.Exists(categoryName)) { // production code should use using _totalImageCounter = new PerformanceCounter(categoryName, counterNameImagesProcessed, false); // production code should use using _imagensPerSecondCounter = new PerformanceCounter(categoryName, counterNameImagesPerSecond, false); return(CreationResult.LoadedCounters); } var counters = new[] { new CounterCreationData(counterNameImagesProcessed, "number of images resized", PerformanceCounterType.NumberOfItems64), new CounterCreationData(counterNameImagesPerSecond, "number of images processed per second", PerformanceCounterType.RateOfCountsPerSecond32) }; var counterCollection = new CounterCreationDataCollection(counters); PerformanceCounterCategory.Create(categoryName, "Image processing information", PerformanceCounterCategoryType.SingleInstance, counterCollection); return(CreationResult.CreatedCounters); }
/// <summary> /// Deletes the performance counters /// </summary> public static void UninstallCustomCounters() { if (m_Sampling) { return; } try { if (!PerformanceCounterCategory.Exists(_Category)) { return; } PerformanceCounterCategory.Delete(_Category); lock (m_SyncRoot) { List <string> delete = new List <string>(); Dictionary <string, PerfHistory> .Enumerator enu = History.GetEnumerator(); while (enu.MoveNext()) { if (enu.Current.Value.Counter.CategoryName == "Wisp") { delete.Add(enu.Current.Key); } } foreach (string key in delete) { History.Remove(key); } } Log1.Logger("Performance").Info("Uninstalled custom performance counters."); } catch (Exception e) { Log1.Logger("Performance").Error("Failed to uninstall custom performance counters.", e); } }
public static void Main(string[] args) { var showHelp = false; var install = false; var uninstall = false; var test = false; var p = new OptionSet(); p.Add("h|help|?", "Displays This", v => showHelp = true); p.Add("i|install", "Installs the Perf Counters", v => install = true); p.Add("u|uninstall", "Installs the Perf Counters", v => uninstall = true); p.Add("t|test", "Tests That The Perf Counters Are Installed", v => test = true); p.Parse(args); if (showHelp) { p.WriteOptionDescriptions(Console.Out); return; } if (install) { PerformanceCounters.InstallCounters(); return; } if (uninstall) { PerformanceCounters.UninstallCounters(); return; } if (test) { Debug.Assert(PerformanceCounterCategory.Exists(PerformanceCounters.CategoryName), "Performance Counter Category Is NOT Installed"); Debug.Assert(PerformanceCounterCategory.CounterExists(PerformanceCounters.TotalMessagesReceived, PerformanceCounters.CategoryName), "Performance Counter Is NOT Installed"); return; } }
// public static methods public static void Install() { if (PerformanceCounterCategory.Exists(CategoryName)) { return; } var properties = GetCounterProperties(); var collection = new CounterCreationDataCollection(); foreach (var property in properties) { var attribute = GetCounterAttribute(property); collection.Add(new CounterCreationData(attribute.Name, attribute.Help, attribute.Type)); } PerformanceCounterCategory.Create( CategoryName, "Stats for the .NET MongoDB Driver.", PerformanceCounterCategoryType.MultiInstance, collection); }
/// <summary> /// Installs the performance counters. /// </summary> public static void InstallCounters() { // Create custom performance counters and counter category var counterCreationDataCollection = new CounterCreationDataCollection(); counterCreationDataCollection.Add(new CounterCreationData("Number of Cached Objects", "The number of objects being stored in the cache", PerformanceCounterType.NumberOfItems64)); counterCreationDataCollection.Add(new CounterCreationData("Cache Memory Usage MB", "The amount of memory used by the cache", PerformanceCounterType.NumberOfItems32)); counterCreationDataCollection.Add(new CounterCreationData("Cache Memory Usage Limit MB", "The maximum amount of memory usable by the cache", PerformanceCounterType.NumberOfItems32)); counterCreationDataCollection.Add(new CounterCreationData("Cache Memory Usage %", "The percentage of usable memory used by the cache", PerformanceCounterType.NumberOfItems32)); counterCreationDataCollection.Add(new CounterCreationData("Total Requests per Second", "The total number of all types of requests per second", PerformanceCounterType.RateOfCountsPerSecond64)); counterCreationDataCollection.Add(new CounterCreationData("Adds per Second", "The number of adds per second", PerformanceCounterType.RateOfCountsPerSecond64)); counterCreationDataCollection.Add(new CounterCreationData("Gets per Second", "The number of gets per second", PerformanceCounterType.RateOfCountsPerSecond64)); counterCreationDataCollection.Add(new CounterCreationData("Removes per Second", "The number of removes per second", PerformanceCounterType.RateOfCountsPerSecond64)); // Delete performance counter category if (PerformanceCounterCategory.Exists(_performanceCounterCategoryName)) { PerformanceCounterCategory.Delete(_performanceCounterCategoryName); } // Create performance counter category PerformanceCounterCategory.Create(_performanceCounterCategoryName, "Performance counters related to Dache services", PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection); }
internal static PerformanceCounter GetCounter(string name, string category) { if (!PerformanceCounterCategory.Exists(category)) { throw new InstrumentationException(Messages.PerformanceCounterHelper_CategoryNotFound, name, category); } if (PerformanceCounterCategory.CounterExists(name, category)) { return(new PerformanceCounter() { CategoryName = category, ReadOnly = false, CounterName = name, MachineName = LOCAL_MACHINE_NAME }); } else { throw new InstrumentationException(Messages.PerformanceCounterHelper_CounterNotFound, name, category); } }
public void CanCreateCategoriesFromConfiguration() { PolicyInjectionSettings settings = new PolicyInjectionSettings(); PolicyData policyData = new PolicyData("Perfmon policy"); //policyData.MatchingRules.Add(new TagAttributeMatchingRuleData("Match By Tag", "Perfmon")); PerformanceCounterCallHandlerData counterData = new PerformanceCounterCallHandlerData("{type}.{method}"); counterData.CategoryName = firstCategory; policyData.Handlers.Add(counterData); settings.Policies.Add(policyData); DictionaryConfigurationSource configSource = new DictionaryConfigurationSource(); configSource.Add(PolicyInjectionSettings.SectionName, settings); PerformanceCountersInstaller installer = new PerformanceCountersInstaller(configSource); CommitInstall(installer); Assert.IsTrue(PerformanceCounterCategory.Exists(firstCategory)); Assert.IsFalse(PerformanceCounterCategory.Exists(secondCategory)); }
private static void CreateCounters() { //delete existing counters if (PerformanceCounterCategory.Exists(CountersCategory)) { PerformanceCounterCategory.Delete(CountersCategory); } //create new counters var counters = new CounterCreationDataCollection { new CounterCreationData(TotalOperationsName, "Total number of random operations performed on the concurrent deque.", PerformanceCounterType.NumberOfItems64), new CounterCreationData(OperationsPerSecondName, "Random operations performed on the concurrent deque per second", PerformanceCounterType.RateOfCountsPerSecond64) }; PerformanceCounterCategory.Create(CountersCategory, "description", PerformanceCounterCategoryType.SingleInstance, counters); }
public static bool Install(Type[] types, bool forceCreate) { ChoGuard.ArgumentNotNull(types, "types"); ChoPerformanceCounterInstallerBuilder builder = new ChoPerformanceCounterInstallerBuilder(types); PerformanceCounterInstaller installer = builder.CreateInstaller(); if (PerformanceCounterCategory.Exists(installer.CategoryName)) { if (forceCreate) { PerformanceCounterCategory.Delete(installer.CategoryName); } else { return(false); } } PerformanceCounterCategory.Create(installer.CategoryName, installer.CategoryHelp, installer.CategoryType, installer.Counters); return(true); }
private static bool SetupCategory() { if (!PerformanceCounterCategory.Exists("AverageCounter64SampleCategory")) { CounterCreationDataCollection CCDC = new CounterCreationDataCollection(); CounterCreationData averageCount64 = new CounterCreationData(); averageCount64.CounterType = PerformanceCounterType.AverageCount64; averageCount64.CounterName = "AverageCounter64Sample"; CCDC.Add(averageCount64); CounterCreationData averageCount64Base = new CounterCreationData(); averageCount64Base.CounterType = PerformanceCounterType.AverageBase; averageCount64Base.CounterName = "AverageCounter64Base"; CCDC.Add(averageCount64Base); PerformanceCounterCategory.Create("AverageCounter64SampleCategory", "Demonstrates usage of the AverageCounter64 performance counter type.", PerformanceCounterCategoryType.MultiInstance, CCDC); return(true); } else { Console.WriteLine("Category exists - AverageCounter64SampleCategory"); return(false); } }
/// <summary> /// This method will create a new counter category. /// sdfsdf /// Note that only one counter is added in this code. /// If more than one counter needs to be created simply copy /// the code that creates the sampleCounter object and add it /// to the counterData array. /// Any counters added to the counterData array will be created /// when you call the Create method on the PerformanceCounterCategory /// object. /// /// Also notice the "SingleInstance" portion of the Create() call. /// This disables multiple instances for the specified counter. /// If you need multiple instances you can simply change "SingleInstance" /// to "MultiInstance" when you call the Create method. /// /// Once the Create() method is called the counter is ready for you to /// write data to it. /// </summary> /// <param name="categoryName">Category name</param> /// <param name="categoryHelp">Category help text</param> /// <param name="categoryType">Category type</param> /// <param name="counterName">Counter name</param> /// <param name="counterHelp">Counter help text</param> /// <param name="counterType">Counter type</param> public static void createCounter( string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp, PerformanceCounterType counterType ) { if (!PerformanceCounterCategory.Exists(categoryName)) { // Create the collection that will hold the data // for the counters we are creating. CounterCreationDataCollection counterData = new CounterCreationDataCollection(); // Create the CreationData object CounterCreationData counter = new CounterCreationData(); // Set the counter's type, name and help text counter.CounterType = counterType; counter.CounterName = counterName; counter.CounterHelp = counterHelp; // Add the creation data object to // our collection counterData.Add(counter); // Create the counter in the system using // the collection PerformanceCounterCategory.Create( categoryName, categoryHelp, categoryType, counterData ); } }
/// <summary> /// Entry point to hook. Verifies that counters exist and initiates timer. /// </summary> public void Initialize() { try { Sitecore.Diagnostics.Log.Info("Initialising CacheCounter hook", this); if (!PerformanceCounterCategory.Exists(CounterCategoryName)) { Sitecore.Diagnostics.Log.Warn("Could not initialise CacheCounter hook - counters did not seem to be present.", this); } _timer.Elapsed += TimerElapsed; _timer.AutoReset = false; _timer.Start(); } catch (Exception ex) { _timer.Stop(); _timer.Elapsed -= TimerElapsed; Sitecore.Diagnostics.Log.Error("Initialisation of CacheCounter hook failed - hook has been disabled.", ex, this); } }
private static PerformanceCounterCategory CreateCategory() { if (PerformanceCounterCategory.Exists(PERFORMANCECOUNTER_CATEGORYNAME)) { PerformanceCounterCategory.Delete(PERFORMANCECOUNTER_CATEGORYNAME); } // start with the built-in counters var currentCounters = new List <CounterCreationData>(); currentCounters.AddRange(_defaultCounters); // add the user-defined custom counters (only the ones that are different from the built-ins) foreach (var customPerfCounter in Logging.CustomPerformanceCounters.Cast <CounterCreationData>(). Where(customPerfCounter => !currentCounters.Any(c => c.CounterName == customPerfCounter.CounterName))) { currentCounters.Add(customPerfCounter); } return(PerformanceCounterCategory.Create(PERFORMANCECOUNTER_CATEGORYNAME, "Performance counters of Sense/Net", PerformanceCounterCategoryType.SingleInstance, new CounterCreationDataCollection(currentCounters.ToArray()))); }
/// <summary> /// installs 4 standard counters for the category provided /// </summary> /// <param name="categoryName"></param> public static void InstallStandardCounters(string categoryName) { if (PerformanceCounterCategory.Exists(categoryName)) { return; } var creationDatas = new CounterHandlerBase[] { new AverageTimeHandler(categoryName, string.Empty), new LastOperationExecutionTimeHandler(categoryName, string.Empty), new TotalCountHandler(categoryName, string.Empty), new NumberOfOperationsPerSecondHandler(categoryName, string.Empty), new CurrentConcurrentCountHandler(categoryName, string.Empty) }.SelectMany(x => x.BuildCreationData()); var counterCreationDataCollection = new CounterCreationDataCollection(); counterCreationDataCollection.AddRange(creationDatas.ToArray()); PerformanceCounterCategory.Create(categoryName, "PerfIt category for " + categoryName, PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection); }
static void InstallPerformanceCounters() { if (!PerformanceCounterCategory.Exists(PerformanceCategoryName)) { CounterCreationData CreationData1 = new CounterCreationData(); CreationData1.CounterName = PerformanceCounterName; CreationData1.CounterHelp = "Number of calls executing per second"; CreationData1.CounterType = PerformanceCounterType.RateOfCountsPerSecond32; CounterCreationData CreationData2 = new CounterCreationData(); CreationData2.CounterName = PerformanceCounterName2; CreationData2.CounterHelp = "Total number of Basic Connection objects created"; CreationData2.CounterType = PerformanceCounterType.NumberOfItems32; CounterCreationData CreationData3 = new CounterCreationData(); CreationData3.CounterName = PerformanceCounterName3; CreationData3.CounterHelp = "Max capacity of the object pool"; CreationData3.CounterType = PerformanceCounterType.NumberOfItems32; CounterCreationData CreationData4 = new CounterCreationData(); CreationData4.CounterName = PerformanceCounterName4; CreationData4.CounterHelp = "Current size of the object pool"; CounterCreationData[] CounterData = { CreationData1, CreationData2, CreationData3, CreationData4 }; PerformanceCounterCategory.Create(PerformanceCategoryName, "DevelopMentor Object Pooling Performance Counters", PerformanceCounterCategoryType.MultiInstance, new CounterCreationDataCollection(CounterData)); } }
static CreationResult SetupPerformanceCounters() { string categoryName = "Image Processing"; if (PerformanceCounterCategory.Exists(categoryName)) { //production code should use using TotalImageCounter = new PerformanceCounter(categoryName: categoryName, counterName: "# of images processed", readOnly: false); //production code should use using ImagesPerSecondCounter = new PerformanceCounter(categoryName: categoryName, counterName: "# images processed per second", readOnly: false); return(CreationResult.LoadedCounters); } CounterCreationData[] counters = new CounterCreationData[] { new CounterCreationData(counterName: "# of images processed", counterHelp: "number of images resized", counterType: PerformanceCounterType.NumberOfItems64), new CounterCreationData(counterName: "# images processed per second", counterHelp: "number of images processed per second", counterType: PerformanceCounterType.RateOfCountsPerSecond32) }; CounterCreationDataCollection counterCollection = new CounterCreationDataCollection(counters); PerformanceCounterCategory.Create(categoryName: categoryName, categoryHelp: "Image processing information", categoryType: PerformanceCounterCategoryType.SingleInstance, counterData: counterCollection); return(CreationResult.CreatedCounters); }
private void InitializeGlobalPerformanceCounters() { try { CounterCreationData[] quickMonCreationData = new CounterCreationData[] { new CounterCreationData("Monitor Packs Loaded", "Monitor Packs Loaded", PerformanceCounterType.NumberOfItems32), new CounterCreationData("Collector execution time/Sec", "Collector executiontime per second", PerformanceCounterType.RateOfCountsPerSecond32) }; if (PerformanceCounterCategory.Exists(Globals.ServiceEventSourceName)) { PerformanceCounterCategory pcC = new PerformanceCounterCategory(Globals.ServiceEventSourceName); if (pcC.GetCounters().Length != quickMonCreationData.Length) { PerformanceCounterCategory.Delete(Globals.ServiceEventSourceName); } } if (!PerformanceCounterCategory.Exists(Globals.ServiceEventSourceName)) { PerformanceCounterCategory.Create(Globals.ServiceEventSourceName, Globals.ServiceEventSourceName, PerformanceCounterCategoryType.SingleInstance, new CounterCreationDataCollection(quickMonCreationData)); } } catch (Exception ex) { EventLog.WriteEntry(Globals.ServiceEventSourceName, string.Format("Create global performance counters category error!: {0}", ex.Message), EventLogEntryType.Error, 10); } try { monitorPacksLoaded = InitializePerfCounterInstance(Globals.ServiceEventSourceName, "Monitor Packs Loaded"); collectionExecutionTimePerSec = InitializePerfCounterInstance(Globals.ServiceEventSourceName, "Collector execution time/Sec"); } catch (Exception ex) { EventLog.WriteEntry(Globals.ServiceEventSourceName, string.Format("Initialize global performance counters error!: {0}", ex.Message), EventLogEntryType.Error, 10); } }
public long GetDatabaseTransactionVersionSizeInBytes() { if (getDatabaseTransactionVersionSizeInBytesErrorValue != 0) { return(getDatabaseTransactionVersionSizeInBytesErrorValue); } try { const string categoryName = "Database ==> Instances"; if (PerformanceCounterCategory.Exists(categoryName) == false) { return(getDatabaseTransactionVersionSizeInBytesErrorValue = -1); } var category = new PerformanceCounterCategory(categoryName); var instances = category.GetInstanceNames(); var ravenInstance = instances.FirstOrDefault(x => x.Contains(uniquePrefix)); const string counterName = "Version Buckets Allocated"; if (ravenInstance == null || !category.CounterExists(counterName)) { return(getDatabaseTransactionVersionSizeInBytesErrorValue = -2); } using (var counter = new PerformanceCounter(categoryName, counterName, ravenInstance, readOnly: true)) { var value = counter.NextValue(); return((long)(value * StorageConfigurator.GetVersionPageSize())); } } catch (Exception e) { if (reportedGetDatabaseTransactionCacheSizeInBytesError == false) { reportedGetDatabaseTransactionCacheSizeInBytesError = true; log.WarnException("Failed to get Version Buckets Allocated value, this error will only be reported once.", e); } return(getDatabaseTransactionVersionSizeInBytesErrorValue = -3); } }
/// <summary> //Se a categoria não existir, crie a categoria e saia. //Os contadores de desempenho não devem ser criados e usados imediatamente. //Há um tempo de latência para ativar os contadores, eles devem ser criados //antes de executar o aplicativo que usa os contadores. //Execute esta amostra uma segunda vez para usar a categoria. /// </summary> /// <returns></returns> public static bool ConfigurarCategoria() { if (!PerformanceCounterCategory.Exists(NomeCategoriaContadores)) { //1) criar uma coleção de dados com CounterCreationDataCollection CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection(); //2) criar os contadores com CounterCreationData CounterCreationData dadosContador = new CounterCreationData(); //3) definir as propriedades do contador dadosContador.CounterType = PerformanceCounterType.AverageTimer32; dadosContador.CounterName = NomeContadorAverageTimer32; counterDataCollection.Add(dadosContador); //2) criar os contadores com CounterCreationData CounterCreationData dadosContadorBase = new CounterCreationData(); //3) definir as propriedades do contador dadosContadorBase.CounterType = PerformanceCounterType.AverageBase; dadosContadorBase.CounterName = NomeContadorAverageTimer32Base; counterDataCollection.Add(dadosContadorBase); //4) criar a categoria e passar a coleção de dados com os contadores PerformanceCounterCategory.Create(NomeCategoriaContadores, "Demonstra o uso do contador de performance de tipo AverageTimer32.", PerformanceCounterCategoryType.SingleInstance, counterDataCollection); Console.WriteLine("Tecle algo para fechar o programa"); Console.WriteLine("e rode novamente para utilizar os contadores de performance."); Console.ReadKey(); return(true); } else { Console.WriteLine("Categoria já existe - " + NomeCategoriaContadores); return(false); } }
public MemoryCachePerformanceCounters(string instanceName, bool noCounters) { var collection = new CounterCreationDataCollection(); if (!noCounters) { if (!PerformanceCounterCategory.Exists(dotNetCategoryName)) { // TODO: check: // // - types of all the counters // CreateCounter("Cache Entries", PerformanceCounterType.NumberOfItems64, collection); CreateCounter("Cache Hit Ratio", PerformanceCounterType.RawFraction, collection); CreateCounter("Cache Hits", PerformanceCounterType.NumberOfItems64, collection); CreateCounter("Cache Misses", PerformanceCounterType.NumberOfItems64, collection); CreateCounter("Cache Trims", PerformanceCounterType.NumberOfItems64, collection); CreateCounter("Cache Turnover Rate", PerformanceCounterType.RateOfCountsPerSecond64, collection); PerformanceCounterCategory.Create(dotNetCategoryName, "System.Runtime.Caching.MemoryCache Performance Counters", PerformanceCounterCategoryType.MultiInstance, collection); } perfCounters = new PerformanceCounter [COUNTERS_LAST + 1]; perfCounters [CACHE_ENTRIES] = new PerformanceCounter(dotNetCategoryName, "Cache Entries", instanceName, false); perfCounters [CACHE_ENTRIES].RawValue = 0; perfCounters [CACHE_HIT_RATIO] = new PerformanceCounter(dotNetCategoryName, "Cache Hit Ratio", instanceName, false); perfCounters [CACHE_HIT_RATIO].RawValue = 0; perfCounters [CACHE_HITS] = new PerformanceCounter(dotNetCategoryName, "Cache Hits", instanceName, false); perfCounters [CACHE_HITS].RawValue = 0; perfCounters [CACHE_MISSES] = new PerformanceCounter(dotNetCategoryName, "Cache Misses", instanceName, false); perfCounters [CACHE_MISSES].RawValue = 0; perfCounters [CACHE_TRIMS] = new PerformanceCounter(dotNetCategoryName, "Cache Trims", instanceName, false); perfCounters [CACHE_TRIMS].RawValue = 0; perfCounters [CACHE_TURNOVER_RATE] = new PerformanceCounter(dotNetCategoryName, "Cache Turnover Rate", instanceName, false); perfCounters [CACHE_TURNOVER_RATE].RawValue = 0; } }
/// <summary> Reclaim memory. </summary> public static void ReclaimMemory() { long mem2 = GC.GetTotalMemory(false); Debug.Print(string.Intern("*** Memory ***")); Debug.Print(string.Intern("\tMemory before GC: ") + ToBytes(mem2)); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); GC.WaitForPendingFinalizers(); long mem3 = GC.GetTotalMemory(false); Debug.Print(string.Intern("\tMemory after GC: ") + ToBytes(mem3)); Debug.Print("\tApp memory being used: " + ToBytes(Environment.WorkingSet)); for (int x = 0; x < GC.MaxGeneration; x++) { Debug.Print("\t\tGeneration " + (x) + " Collection Count: " + GC.CollectionCount(x)); } const string category = ".NET CLR Memory"; const string counter = "% Time in GC"; string instance = Process.GetCurrentProcess().ProcessName; if (PerformanceCounterCategory.Exists(category) && PerformanceCounterCategory.CounterExists(counter, category) && PerformanceCounterCategory.InstanceExists(instance, category)) { var gcPerf = new PerformanceCounter(category, counter, instance); float percent = gcPerf.NextValue(); string suffix = "%"; if (percent > 50.0) { suffix += " <- High Watermark Warning"; } Debug.Print("\t\tTime Spent in GC: " + $"{percent:00.##}" + suffix); } Debug.Print(string.Intern("*** Memory ***")); }
internal void SetInstanceName(string instanceName) { PerformanceCounterData[] dataArray = s_DefaultPerformanceCounters; if (string.IsNullOrEmpty(instanceName)) { try { new SecurityPermission(PermissionState.Unrestricted).Assert(); instanceName = Process.GetCurrentProcess().MainModule.ModuleName; } finally { CodeAccessPermission.RevertAssert(); } } this.m_instanceName = instanceName; Dictionary <PerformanceCounterAction, List <PerformanceCounterStatement> > dictionary = new Dictionary <PerformanceCounterAction, List <PerformanceCounterStatement> >(); if (PerformanceCounterCategory.Exists(c_PerformanceCounterCategoryName)) { for (int i = 0; i < dataArray.Length; i++) { PerformanceCounterData data = dataArray[i]; for (int j = 0; j < data.Mappings.Length; j++) { PerformanceCounterActionMapping mapping = data.Mappings[j]; if (!dictionary.ContainsKey(mapping.Action)) { dictionary.Add(mapping.Action, new List <PerformanceCounterStatement>()); } List <PerformanceCounterStatement> list = dictionary[mapping.Action]; PerformanceCounterStatement item = new PerformanceCounterStatement(this.CreateCounters(data.Name), mapping.Operation); list.Add(item); } } } this.m_actionStatements = dictionary; }
public static void SetupCategory() { if (!PerformanceCounterCategory.Exists(CATEGORY_NAME)) { var CCDC = new CounterCreationDataCollection(); var a = new CounterCreationData(); a.CounterType = PerformanceCounterType.RateOfCountsPerSecond64; a.CounterName = "Invoked Count/sec"; CCDC.Add(a); var b = new CounterCreationData(); b.CounterType = PerformanceCounterType.AverageTimer32; b.CounterName = "Average Duration/sec"; //CCDC.Add(b); //CounterCreationData c = new CounterCreationData(); //c.CounterType = PerformanceCounterType.AverageTimer32; //c.CounterName = "Message Size/sec"; //CCDC.Add(c); var d = new CounterCreationData(); d.CounterType = PerformanceCounterType.RateOfCountsPerSecond64; d.CounterName = "Server Fault/sec"; CCDC.Add(d); var e = new CounterCreationData(); e.CounterType = PerformanceCounterType.AverageBase; e.CounterName = "Invoked Count"; //CCDC.Add(e); PerformanceCounterCategory.Create(CATEGORY_NAME, NAME, PerformanceCounterCategoryType.MultiInstance, CCDC); PerformanceCounterCategory.Create(CATEGORY_NAME + " Global", NAME, PerformanceCounterCategoryType.SingleInstance , new CounterCreationDataCollection { b, e }); } }