private static void Dispose(PerformanceCounter counter) { if (null != counter) { counter.RemoveInstance(); counter.Dispose(); } }
public void Dispose() { if (!disposed) { disposed = true; } else { return; } if (_performanceCounter != null) { _performanceCounter.Dispose(); } }
public void GetPerformanceCounter() { var counter = new System.Diagnostics.PerformanceCounter { CategoryName = "Distracey.Examples.Website-ApiFilter", InstanceName = "Default", CounterName = "ValuesController.Get(Int32 id) - GET - Average seconds taken to execute", ReadOnly = false, InstanceLifetime = PerformanceCounterInstanceLifetime.Process, }; counter.RawValue = 0; const int value = 100; counter.IncrementBy(value); System.Diagnostics.PerformanceCounter.CloseSharedResources(); Assert.AreEqual(value, counter.RawValue); counter.RemoveInstance(); counter.Dispose(); }
/// <summary> /// Returnes cpu usage of a specific process /// </summary> /// <param name="jobId">Id of executing job</param> /// <param name="clientId">Id of executor client</param> /// <param name="processName">name of the process</param> /// <returns>ServiceOutput object</returns> public static ServiceOutput GetCpuUsageOfSpecificProcess(long jobId, long clientId, string processName) { PerformanceCounter cpuCounter; var sum = (float)0; try { var processes = Process.GetProcessesByName(processName); foreach (var process in processes) { cpuCounter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName, true); cpuCounter.NextValue(); Thread.Sleep(250); sum += cpuCounter.NextValue(); cpuCounter.Dispose(); } return new ServiceOutput() { JobId = jobId, ClientId = clientId, Result = (long) sum, Duration = -1, Date = DateTime.Now }; } catch { return new ServiceOutput() { JobId = jobId, ClientId = clientId, Result = -1, Duration = -1, Date = DateTime.Now }; } }
//private static float GetPerformanceCounterValueByInstanceDeux(string perfCategory, string perfCounterName, string perfInstanceName, out string PerfCounterType, int sleep = 50) //{ // pCounter = new PerformanceCounter(); // PerfCounterType = ""; // try // { // pCounter.CategoryName = perfCategory; // pCounter.CounterName = perfCounterName; // pCounter.InstanceName = perfInstanceName; // try // { // pCounter.NextValue(); // pFirstSample = pCounter.NextSample(); // Thread.Sleep(sleep); // float nv = pCounter.NextValue(); // pSecondSample = pCounter.NextSample(); // float avg = CounterSample.Calculate(pFirstSample, pSecondSample); // Console.WriteLine("{0}, {1}", nv, avg); // return avg; // } // finally // { // pCounter.Dispose(); // } // } // catch // { // try // { // PerformanceCounter pc = new PerformanceCounter(LookupPerfNameByName(perfCategory), LookupPerfNameByName(perfCounterName), perfInstanceName); // pc.NextValue(); // Thread.Sleep(sleep); // try // { // PerfCounterType = pc.CounterType.ToString(); // return pc.NextValue(); // } // finally // { // pc.Dispose(); // } // } // catch // { // // I give up, didnt manage to figure out the correct name for the PerformanceCounter. // Console.WriteLine("ERROR: Error looking up PerformanceCounter '" + perfCategory + "\\" + perfCounterName + "' for " + perfInstanceName + "'"); // return -1; // } // } //} public static string GetPerformanceCounterValueAsString(string perfCategory, string perfCounterName, out string PerfCounterType, int sleep = 50) { //float badresult = -1; try { PerformanceCounter pc = new PerformanceCounter(perfCategory, perfCounterName); pc.NextValue(); Console.WriteLine(pc.NextSample()); Thread.Sleep(sleep); try { PerfCounterType = pc.CounterType.ToString(); return pc.NextValue().ToString("0.0"); } finally { pc.Dispose(); } //return pc.RawValue; } catch { try { PerformanceCounter pc = new PerformanceCounter(LookupPerfNameByName(perfCategory), LookupPerfNameByName(perfCounterName)); pc.NextValue(); Thread.Sleep(sleep); try { PerfCounterType = pc.CounterType.ToString(); return pc.NextValue().ToString("0.0"); } finally { pc.Dispose(); } } catch { // I give up, didnt manage to figure out the correct name for the PerformanceCounter. Console.WriteLine("ERROR: Error looking up PerformanceCounter '" + perfCategory + "\\" + perfCounterName + "'"); PerfCounterType = "missing"; return "missing"; } } }
void CollectServerInfo(string logFileCollectionPath = "") { // The Basics string serverInfo = "Name: " + Name + "\r\n" + "IPAddress: " + IPAddress + "\r\n" + "Fully Qualified Domain Name: " + FullyQualifiedDomainName + "\r\n\r\n"; // Performance numbers PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Name); PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes", String.Empty, Name); serverInfo += String.Format("Processor Usage: {0:##0} %\r\n", cpuCounter.NextValue()); serverInfo += String.Format("Available RAM: {0} MB\r\n", ramCounter.NextValue()); cpuCounter.Dispose(); ramCounter.Dispose(); // Revit Servers foreach (string version in RevitServer.Versions()) { serverInfo += "______________________________________________________________________________\r\n" + "Revit Server " + version + "\r\n"; bool versionExists = false; foreach (RevitServer rs in RevitServers) { if (rs.Version == version) { versionExists = true; break; } } if (!versionExists) { serverInfo += "Not Configured.\r\n" ; } else { foreach (RevitServer rs in RevitServers) { if (rs.Version == version) { // Revit Server roles for this version serverInfo += "Roles: " + rs.RolesAsString() + "\r\n"; // Location of project data serverInfo += "Project Data Location: " + rs.ProjectDataPath + "\r\n"; // Contents of RSN.ini if (rs.Hosts.Count > 0) { serverInfo += "Hosts in RSN.ini:\r\n"; int counter = 1; foreach (string host in rs.Hosts) { serverInfo += " " + counter.ToString() +". " + host + " - latency from this machine: " + GetPingTimeString(host) + "\r\n"; counter += 1; } } else { serverInfo += "Hosts are not properly configured, or RSN.ini is missing."; } break; } } } } serverInfo += GetRunningProcesses(); serverInfo += "______________________________________________________________________________\r\n"; // Write the data Logging.RsiLog(serverInfo); System.IO.File.WriteAllText(logFileCollectionPath + "\\_ServerInfo.txt", @serverInfo); }
public void TestMergeTableTiming(int mergeMax, int size) { PerformanceCounter PC = new PerformanceCounter(); PC.CategoryName = "Process"; PC.CounterName = "Working Set - Private"; PC.InstanceName = Process.GetCurrentProcess().ProcessName; Console.WriteLine("TESTING: page max({0}) record count({1})", mergeMax, size); var basename = "RazorDbTests.IndexingTests"; var rand = new Random((int)DateTime.Now.Ticks); var indexHash = new Dictionary<ByteArray, byte[]>(); var itemKeyLen = 35; var kvsName = string.Format("MergeTableTiming_{0}_{1}", mergeMax, DateTime.Now.Ticks); var sw = new Stopwatch(); sw.Start(); using (var testKVS = new KeyValueStore(Path.Combine(basename, kvsName))) { // add a bunch of values that look like indexes for (int r = 0; r < size; r++) { var indexLen = (int)(DateTime.Now.Ticks % 60) + 50; var indexKeyBytes = dataset[r]; var valuekeyBytes = indexKeyBytes.Skip(indexKeyBytes.Length - itemKeyLen).ToArray(); testKVS.Set(indexKeyBytes, valuekeyBytes); // old style index indexHash.Add(new ByteArray(valuekeyBytes), indexKeyBytes); } TableManager.RunTableMergePass(testKVS); } sw.Stop(); var memsize = Convert.ToInt32(PC.NextValue()) / (int)(1024); Console.WriteLine("Total processing time: {0} entries {1} mergeSz {2} MEMORY: {3}", size, mergeMax, sw.Elapsed.ToString(), memsize); Console.WriteLine(); PC.Close(); PC.Dispose(); }
public void _Update_RAM() { string[] separators = { ",", ";", ":" }; string value = textBox3.Text; string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries); try { Process[] processes = Process.GetProcessesByName(words[0]); int pL = processes.Length; count = processes.Length; if (pL > 0) { for (int i = 0; i < processes.Length; i++) { if (pL > listView1.Items.Count) { cpuUsage.Add(i); cpuOld.Add(i); pMem.Add(i); } if (i == 0) { PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set - Private", words[0]); pMem[i] = Convert.ToInt32(ramCounter.NextValue()) / (int)(1024); ramCounter.Dispose(); } else if (i > 0) { PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set - Private", string.Concat(words[0], "#", i)); pMem[i] = Convert.ToInt32(ramCounter.NextValue()) / (int)(1024); ramCounter.Dispose(); } #region AddItem //Currently only accepting the first argument //This works for single process monitoring eg "game;" //for multiple processes "game;game1;game2;game3;" this will need reworked. try { if (pL > listView1.Items.Count) { //Add Items/SubItems item = new ListViewItem(processes[i].ProcessName); item.SubItems.Add("0%"); item.SubItems.Add(pMem[i].ToString("#,#") + " K"); listView1.Items.Add(item); } else if (pL < listView1.Items.Count) { //Remove Item/SubItems listView1.Items.RemoveAt(i); cpuUsage.RemoveAt(i); cpuOld.RemoveAt(i); pMem.RemoveAt(i); return; } else if (pL == listView1.Items.Count) { //Update Item/SubItem listView1.Items[i].SubItems[0].Text = processes[i].ProcessName; listView1.Items[i].SubItems[2].Text = pMem[i].ToString("#,#") + " K"; } } catch (Exception) { } #endregion } } else if (processes.Length == 0 && listView1.Items.Count > processes.Length) { listView1.Items.Clear(); cpuUsage.Clear(); cpuOld.Clear(); pMem.Clear(); } else return; } catch (Exception) { } }
private void Process() { while (!finalizeService) { PerformanceCounter PC = new PerformanceCounter(); PC.CategoryName = "Processor"; PC.CounterName = "% Processor Time"; PC.InstanceName = "_Total"; PC.ReadOnly = true; var value = PC.NextValue(); Thread.Sleep(1000); value = PC.NextValue(); PC.Close(); PC.Dispose(); PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes", true); var ramValue = ramCounter.NextValue(); if (ramValue < MinRAMAvailable) { SendAlertMessage(AlertType.RAM_ALERT, value,Convert.ToInt64(ramValue)); } if (value > MaxCPUUsage) { totalHits = totalHits + 1; if (totalHits == Period) { SendAlertMessage(AlertType.PROCESS_ALERT, value, Convert.ToInt64(ramValue)); totalHits = 0; } } else { totalHits = 0; } } eventLog.WriteEntry(ServiceName + " stoped."); }
protected string GetAvailableMemory() { PerformanceCounter counter = null; try { counter = new PerformanceCounter("Memory", "Available MBytes"); return counter.NextValue().ToString(CultureInfo.InvariantCulture); } catch { return "Error"; } finally { if (counter != null) { counter.Dispose(); } } }
private PerformanceCounter ObjectsInReferenceSystemCounterFor(IObjectContainer container) { if (_objectsCounter == null) { _objectsCounter = Db4oPerformanceCounters.CounterFor(PerformanceCounterSpec.ObjectReferenceCount, container, false); var eventRegistry = EventRegistryFactory.ForObjectContainer(container); eventRegistry.Closing += delegate { _objectsCounter.RemoveInstance(); _objectsCounter.Dispose(); }; } return _objectsCounter; }
private static void collectMetrics(object state) { StateControl control = state as StateControl; if (control.IsRunning) return; // skip this run if we're already collecting data control.IsRunning = true; // restore configured culture setting for this async thread Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(conf.DefaultCulture); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(conf.DefaultCulture); // collect metric samples for each of our counters foreach (Config.PerformanceCounterElement counterConfig in Config.CarbonatorSection.Current.Counters) { float sampleValue = 0f; string metricPath = getMetricPath(counterConfig.Path); // counter in list var perfCounterEntry = _counters.FirstOrDefault(c => c.Item1 == counterConfig.CategoryName && c.Item2 == counterConfig.CounterName && c.Item3 == counterConfig.InstanceName); if (perfCounterEntry == null) { PerformanceCounter counter = null; try { counter = new PerformanceCounter(counterConfig.CategoryName, counterConfig.CounterName, counterConfig.InstanceName); counter.NextValue(); perfCounterEntry = new Tuple<string, string, string, PerformanceCounter>(counterConfig.CategoryName, counterConfig.CounterName, counterConfig.InstanceName, counter); } catch (Exception any) { if (counter != null) counter.Dispose(); if (Config.CarbonatorSection.Current.LogLevel >= 2) EventLog.WriteEntry(Program.EVENT_SOURCE, string.Format("Unable to initialize performance counter with path '{0}': {1}", metricPath, any.Message), EventLogEntryType.Warning); continue; } _counters.Add(perfCounterEntry); } try { sampleValue = perfCounterEntry.Item4.NextValue(); } catch (Exception any) { if (Config.CarbonatorSection.Current.LogLevel >= 2) EventLog.WriteEntry(Program.EVENT_SOURCE, string.Format("Unable to collect performance counter with path '{0}': {1}", metricPath, any.Message), EventLogEntryType.Warning); // remove from list perfCounterEntry.Item4.Dispose(); _counters.Remove(perfCounterEntry); continue; } // BlockingCollection will halt this thread if we are exceeding capacity _metricsList.Add(new CollectedMetric(metricPath, sampleValue)); } control.IsRunning = false; }
public void _CPU_Usage() { try { string[] separators = { ",", ";", ":" }; string value = textBox3.Text; string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries); Process[] processes = Process.GetProcessesByName(words[0]); int pL = processes.Length; if (pL > 0) { int sleep = 150 / countClients() + 50; for (int i = 0; i < processes.Length; i++) { try { PerformanceCounter tt = new PerformanceCounter("Process", "% Processor Time", "_Total", true); if (i == 0) { PerformanceCounter tp = new PerformanceCounter("Process", "% Processor Time", words[0], true); tp.NextValue(); tt.NextValue(); Thread.Sleep(sleep); cpuUsage[i] = Math.Round(tp.NextValue() / tt.NextValue() * 100, 1); tp.Dispose(); } else if (i > 0) { PerformanceCounter tp = new PerformanceCounter("Process", "% Processor Time", string.Concat(words[0], "#", i), true); tp.NextValue(); tt.NextValue(); Thread.Sleep(sleep); cpuUsage[i] = Math.Round(tp.NextValue() / tt.NextValue() * 100, 1); tp.Dispose(); } if (Double.IsNaN(cpuUsage[i]) || Double.IsInfinity(cpuUsage[i])) { cpuUsage[i] = cpuOld[i]; } else { cpuOld[i] = cpuUsage[i]; } tt.Dispose(); } catch (Exception) { } } } else return; } catch (Exception) { } }
private static void collectMetrics(object state) { StateControl control = state as StateControl; if (control.IsRunning) return; // skip this run if we're already collecting data control.IsRunning = true; // restore configured culture setting for this async thread Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(conf.DefaultCulture); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(conf.DefaultCulture); // determine how long it takes for us to collect metrics // we'll adjust timer so that collecting this data is slightly more accurate // but not too much to cause skew in performance (e.g. our CPU usage goes up when we do this) Stopwatch timeTaken = new Stopwatch(); timeTaken.Start(); // collect metric samples for each of our counters foreach (Config.PerformanceCounterElement counterConfig in Config.CarbonatorSection.Current.Counters) { float sampleValue = 0f; string metricPath = getMetricPath(counterConfig.Path); // counter in list var perfCounterEntry = _counters.FirstOrDefault(c => c.Item1 == counterConfig.CategoryName && c.Item2 == counterConfig.CounterName && c.Item3 == counterConfig.InstanceName); if (perfCounterEntry == null) { PerformanceCounter counter = null; try { counter = new PerformanceCounter(counterConfig.CategoryName, counterConfig.CounterName, counterConfig.InstanceName); counter.NextValue(); perfCounterEntry = new Tuple<string, string, string, PerformanceCounter>(counterConfig.CategoryName, counterConfig.CounterName, counterConfig.InstanceName, counter); } catch (Exception any) { if (counter != null) counter.Dispose(); if (Config.CarbonatorSection.Current.LogLevel >= 2) EventLog.WriteEntry(Program.EVENT_SOURCE, string.Format("Unable to initialize performance counter with path '{0}': {1}", metricPath, any.Message), EventLogEntryType.Warning); continue; } _counters.Add(perfCounterEntry); } try { sampleValue = perfCounterEntry.Item4.NextValue(); } catch (Exception any) { if (Config.CarbonatorSection.Current.LogLevel >= 2) EventLog.WriteEntry(Program.EVENT_SOURCE, string.Format("Unable to collect performance counter with path '{0}': {1}", metricPath, any.Message), EventLogEntryType.Warning); // remove from list perfCounterEntry.Item4.Dispose(); _counters.Remove(perfCounterEntry); continue; } // BlockingCollection will halt this thread if we are exceeding capacity _metricsList.Add(new CollectedMetric(metricPath, sampleValue)); } timeTaken.Stop(); // adjust how often we collect metrics to stay within hysteresis int periodTime = (int)Math.Abs(1000 - (int)timeTaken.ElapsedMilliseconds); if (periodTime > 100 && periodTime <= 1000) { _metricCollectorTimer.Change(100, periodTime); if (Config.CarbonatorSection.Current.LogLevel >= 4) EventLog.WriteEntry(Program.EVENT_SOURCE, string.Format("Adjusted _metricCollector periodTime={0}ms", periodTime), EventLogEntryType.Information); } control.IsRunning = false; }
public override async Task<State> Poll() { ServerManager server = null; ObjectState stateResult = ObjectState.Unknown; State state = default(State); try { server = ServerManager.OpenRemote(serverInstance.Name) ; if (server != null&& this.Exist()) { state = new State(); state.Url = string.Concat(this.Name, "@", serverInstance.Name); stateResult = server.ApplicationPools[Name].State; if (stateResult == ObjectState.Started) { if (server.ApplicationPools[Name].WorkerProcesses.Count > 0) { WorkerProcess wp = server.ApplicationPools[Name].WorkerProcesses .Where(p => p .AppPoolName.ToLowerInvariant() == Name.ToLowerInvariant()) .FirstOrDefault(); PerformanceCounter cpuCounter = new PerformanceCounter("Process" , "% Processor Time" , Process.GetProcessById(wp.ProcessId, serverInstance.Name).ProcessName , serverInstance.Name); cpuPercent = cpuCounter.NextValue(); await Task.Delay(2000); cpuPercent = cpuCounter.NextValue(); await Task.Delay(30000); //the requests interval time is now 30000 int numOfRequests = wp.GetRequests(30000).Count; float cpuPercentAfterThirthySeconds = cpuCounter.NextValue(); if (cpuPercent >= _cpuAlertTreshold && cpuPercentAfterThirthySeconds >= _cpuAlertTreshold) { state.Status = "High CPU Load"; state.Description =string.Format("The CPU for app pool {0} on {1} has reach {2}% and may cause HTTP 503 errors", Name, serverInstance.Name, cpuPercent); state = GetCommonState(server, state, numOfRequests); } else { state.Status = _positiveStatusCode; } if (!string.IsNullOrEmpty(state.Status)) { server.Dispose(); cpuCounter.Close(); cpuCounter.Dispose(); } } else { state.Status = _positiveStatusCode; } return state; } else { state.Description = stateResult == ObjectState.Started ? string.Format("The app pool on server {0} is in the following in {1} state, the number of worker processes is {2}", serverInstance.Name, stateResult.ToString(), server.ApplicationPools[Name].WorkerProcesses.Count) : "Unavailable"; state.Status = stateResult == ObjectState.Started ? _positiveStatusCode: "App Pool Not Started"; state = GetCommonState(server, state, 0); if (stateResult == ObjectState.Stopped) { server.ApplicationPools[Name].Start(); state.Description += server.ApplicationPools[Name].State == ObjectState.Started ? "\rResolution: The appPool was started" : state.Description; } } } } catch(Exception ex) { state.Status = ex.GetType().Name; state.Description = "'polling failed with" + ex.Message; state.Url = string.Concat(this.Name, "@", serverInstance.Name); return state; } return state; }
// Try to discover GUID from buggy Performance Monitor instance names. // Note: Discover drive GUID comparing free space is uggly, but MS gave me no choice. static LogicalDisk() { // ===== WMI ===== Win32_Volume[] vols = Win32_Volume.GetAllVolumes(); // Free megabytes and volume GUID relation Dictionary<ulong, Guid> wmiFree = new Dictionary<ulong, Guid>(vols.Length); // Volume name and volume GUID relation Dictionary<string, Guid> wmiName = new Dictionary<string, Guid>(vols.Length); foreach (Win32_Volume v in vols) { if (v.Automount && v.DriveType == System.IO.DriveType.Fixed) { if (v.IsMounted) { wmiName.Add(v.Name.TrimEnd('\\'), v.DeviceGuid); } else { wmiFree.Add(v.FreeSpace / MB_MULT, v.DeviceGuid); } } } perfMonGuid = new Dictionary<Guid, string>(wmiFree.Count + wmiName.Count); // ===== PERFORMANCE MONITOR ====== PerformanceCounterCategory perfCat = new PerformanceCounterCategory( Localization.GetName(COUNTER_LOGICAL_DISK)); // TODO: Find a faster way to get instance names. string[] instances = perfCat.GetInstanceNames(); // Free megabytes and Performance Monitor instance name Dictionary<ulong, string> perfFree = new Dictionary<ulong, string>(instances.Length); foreach (string item in instances) { if (item == "_Total") continue; Guid volId = Guid.Empty; if (wmiName.TryGetValue(item, out volId)) { perfMonGuid.Add(volId, item); } else { PerformanceCounter p = new PerformanceCounter( Localization.GetName(COUNTER_LOGICAL_DISK), Localization.GetName(COUNTER_FREE_MB), item); perfFree.Add((ulong)p.RawValue, item); p.Close(); p.Dispose(); } } ulong[] warray = new ulong[wmiFree.Count]; ulong[] pmarray = new ulong[perfFree.Count]; if (warray.Length != pmarray.Length) throw new NotSupportedException(MSG_EXCEPTION); wmiFree.Keys.CopyTo(warray, 0); perfFree.Keys.CopyTo(pmarray, 0); Array.Sort<ulong>(warray); Array.Sort<ulong>(pmarray); for (int i = 0; i < warray.Length; i++) { perfMonGuid.Add(wmiFree[warray[i]], perfFree[pmarray[i]]); } }
static void CollectingMemory() { Process currentProcess = Process.GetCurrentProcess(); var privateByteCounter = new PerformanceCounter("Process", "Working Set - Private", currentProcess.ProcessName); var netMemoryCounter = new PerformanceCounter(".NET CLR Memory", "# Bytes in all Heaps", currentProcess.ProcessName); while (!done) { maxNetMemory = Math.Max(netMemoryCounter.NextSample().RawValue / 1024, maxNetMemory); maxPrivateWorkingSet = Math.Max(privateByteCounter.NextSample().RawValue / 1024, maxPrivateWorkingSet); Thread.Sleep(100); } privateByteCounter.Dispose(); netMemoryCounter.Dispose(); }