static float Calculate(CounterSample oldSample, CounterSample newSample) { switch (newSample.CounterType) { case PerformanceCounterType.CounterTimer: { float elapsedTime = 1e-7f * (newSample.TimeStamp100nSec - oldSample.TimeStamp100nSec); float elapsedClocks = newSample.SystemFrequency * elapsedTime; float sampleDiff = newSample.RawValue - oldSample.RawValue; float result = sampleDiff / elapsedClocks * 100; return(result); } case PerformanceCounterType.Timer100Ns: { float elapsed100ns = newSample.TimeStamp100nSec - oldSample.TimeStamp100nSec; float sampleDiff = newSample.RawValue - oldSample.RawValue; float result = sampleDiff / elapsed100ns * 100; return(result); } default: return(CounterSample.Calculate(oldSample, newSample)); } }
public List <MetricResult> Collect() { InitCounters(); return(_counters.Select(x => new MetricResult { Path = _configurationFile.Host + "." + x.Alias, Alias = x.Alias, Timestamp = DateTime.Now, Value = x.Counters.Sum(z => { try { var cs1 = z.NextSample(); Thread.Sleep(500); var cs2 = z.NextSample(); return CounterSample.Calculate(cs1, cs2); } catch (Exception e) { _logger.Debug($"Failed to get metric - {x.Name}", e); return 0; } }) }).ToList()); }
public static void CounterSample_Calculate_CalculateCounterSampleCounterSample() { CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32); CounterSample counterSample2 = new CounterSample(15, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32); Assert.Equal(10, CounterSample.Calculate(counterSample1, counterSample2)); }
private float GetValue() { CounterSample currentSample = _perfCounter.NextSample(); if (currentSample.SystemFrequency != 0) { // The recommended delay time between calls to the NextSample method is one second, to allow the counter to perform the next incremental read. float timeDifferenceSecs = (currentSample.TimeStamp - _nextSample.TimeStamp) / (float)currentSample.SystemFrequency; if (timeDifferenceSecs > 0.5F || timeDifferenceSecs < -0.5F) { _prevSample = _nextSample; _nextSample = currentSample; if (_prevSample.Equals(CounterSample.Empty)) { _prevSample = currentSample; } } } else { _prevSample = _nextSample; _nextSample = currentSample; } float sampleValue = CounterSample.Calculate(_prevSample, currentSample); return(sampleValue); }
public int GetCPUTotalUsage() { int num = 0; try { if (this.newValue.BaseValue == 0L) { this.newValue = Cpu_Counter.NextSample(); return(0); } this.oldValue = this.newValue; this.newValue = Cpu_Counter.NextSample(); float num2 = CounterSample.Calculate(this.oldValue, this.newValue); num = (int)num2; if (num2 * 10f % 10f >= 5f) { num = (int)num2 + 1; } if (num > 100) { num = 100; } } catch (Exception) { num = -1; } return(num); }
public PerformanceInfo CheckParameters() { PerformanceInfo perfInfo = new PerformanceInfo(); var today = DateTime.Now; PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); PerfomanceInfoData perfData = PsApiWrapper.GetPerformanceInfo(); CounterSample cs1 = cpuCounter.NextSample(); System.Threading.Thread.Sleep(100); CounterSample cs2 = cpuCounter.NextSample(); perfInfo.CpuPercentUsage = CounterSample.Calculate(cs1, cs2); perfInfo.CommitTotalPages = perfData.CommitTotalPages; perfInfo.PageSizeMB = Math.Round((double)perfData.PageSizeBytes / 1024 / 1024, 2, MidpointRounding.AwayFromZero); perfInfo.PhysicalAvailableMB = Math.Round((double)perfData.PhysicalAvailableBytes / 1024 / 1024, 2, MidpointRounding.AwayFromZero); perfInfo.PhysicalTotalMB = Math.Round((double)perfData.PhysicalTotalBytes / 1024 / 1024, 2, MidpointRounding.AwayFromZero); perfInfo.ThreadCount = perfData.ThreadCount; perfInfo.ProcessCount = perfData.ProcessCount; perfInfo.Time = today.ToString("yyyy-MM-dd HH:mm:ss"); logger.Info("Performance details chcecked succesfully"); return(perfInfo); }
protected void GenerarGraficoActividadDisco() { PerformanceCounter cpuCounter = new PerformanceCounter("PhysicalDisk", "% Disk Time", "_Total"); CounterSample cs1 = cpuCounter.NextSample(); System.Threading.Thread.Sleep(100); CounterSample cs2 = cpuCounter.NextSample(); double PorcentajeUtilizado = Math.Round(CounterSample.Calculate(cs1, cs2), 2); double PorcentajeLibre = 100 - PorcentajeUtilizado; double[] yValues = { PorcentajeUtilizado, PorcentajeLibre }; string[] xValues = { "Utilizado: " + PorcentajeUtilizado.ToString() + "%", "Disponible: " + PorcentajeLibre.ToString() + "%" }; chartDiscoAc.Series["Default"].Points.DataBindXY(xValues, yValues); chartDiscoAc.Series["Default"].Points[0].Color = Color.DarkGoldenrod; chartDiscoAc.Series["Default"].Points[1].Color = Color.PaleGoldenrod; chartDiscoAc.Series["Default"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Pie; chartDiscoAc.Series["Default"]["PieLabelStyle"] = "Disabled"; chartDiscoAc.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true; chartDiscoAc.Legends[0].Enabled = false; }
public TimeSpan ExecuteProbe() { if (_perfCounter == null) { try { if (!StartProbe(true)) { return(ProbeFrequency); } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(_traceSource.Name + " " + ex.Message); TraceEvent(TraceEventType.Critical, float.NaN, CategoryName + ": " + ex.Message); return(ProbeFrequency); } } try { float value = 0; CounterSample curr = _perfCounter.NextSample(); switch (_perfCounter.CounterType) { case PerformanceCounterType.NumberOfItemsHEX32: case PerformanceCounterType.NumberOfItemsHEX64: case PerformanceCounterType.NumberOfItems32: case PerformanceCounterType.NumberOfItems64: { value = CounterSample.Calculate(curr); } break; default: { value = CounterSample.Calculate(_prevSample.Value, curr); } break; } _prevSample = curr; TraceEvent(TraceEventType.Information, value, "Ok"); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(_traceSource.Name + " " + ex.Message); try { StartProbe(true); } catch (Exception startEx) { System.Diagnostics.Trace.WriteLine(_traceSource.Name + " " + startEx.Message); TraceEvent(TraceEventType.Critical, float.NaN, ex.Message); // Report initial exception } } return(ProbeFrequency); }
private static void Record(CrankArguments arguments) { var maxConnections = 0; foreach (var sample in _samples) { // metric simplified for reporting to reflect the counter name and machine where it was sampled var key = String.Format("{0} ({1})", sample.Key.CounterName, ExpandMachineName(sample.Key.MachineName)); var samples = sample.Value; var values = new long[samples.Count - 1]; for (int i = 0; i < values.Length; i++) { values[i] = (long)Math.Round(CounterSample.Calculate(samples[i], samples[i + 1])); Mark(arguments, (ulong)values[i], key); } if (key.StartsWith("Connections Connected")) { maxConnections = (int)Math.Max(maxConnections, values.Max()); } RecordAggregates(key, values); } Console.WriteLine("Max Connections Connected: " + maxConnections); }
internal float Sample(string counterName) { PerfData perfData = _counters[counterName]; return(perfData != null ? CounterSample.Calculate(perfData.Samples[0], perfData.Counter.NextSample()) : 0); }
public float GetMemoryTotal() { CounterSample m1 = memoryTotal.NextSample(); System.Threading.Thread.Sleep(1000); CounterSample m2 = memoryTotal.NextSample(); return(CounterSample.Calculate(m1, m2)); }
// example : https://www.andygup.net/a-better-way-to-measure-cpu-using-windows-performancecounter-and-c/ public float GetCpuTotal() { CounterSample c1 = cpuTotal.NextSample(); System.Threading.Thread.Sleep(1000); CounterSample c2 = cpuTotal.NextSample(); return(CounterSample.Calculate(c1, c2)); }
public float GetDiskTime() { CounterSample d1 = diskTime.NextSample(); System.Threading.Thread.Sleep(1000); CounterSample d2 = diskTime.NextSample(); return(CounterSample.Calculate(d1, d2)); }
public static float GetCurrentCpuPercentage() { var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); CounterSample cpuCounterSample1 = cpuCounter.NextSample(); System.Threading.Thread.Sleep(500); CounterSample cpuCounterSample2 = cpuCounter.NextSample(); return(CounterSample.Calculate(cpuCounterSample1, cpuCounterSample2)); }
//calculates the global cpu usage with the performanceCounterCPU void getCpuUsage() { CounterSample cs1 = performanceCounterCPU.NextSample(); System.Threading.Thread.Sleep(100); CounterSample cs2 = performanceCounterCPU.NextSample(); float cpuUsage = CounterSample.Calculate(cs1, cs2); cpuUsage = (cpuUsage < 1.00f) ? 1.00f : cpuUsage; CpuUsageValueLabel.Text = string.Format("{0:#,###.##} %", cpuUsage); }
public void Display() { PerformanceCounter theCPUCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); CounterSample cs1 = theCPUCounter.NextSample(); Thread.Sleep(100); CounterSample cs2 = theCPUCounter.NextSample(); float finalCpuCounter = CounterSample.Calculate(cs1, cs2); Console.WriteLine("Total Cpu Usage:" + finalCpuCounter); }
private void GetCPUStatus() { PerformanceCounter theCPUCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); CounterSample cs1 = theCPUCounter.NextSample(); Thread.Sleep(100); CounterSample cs2 = theCPUCounter.NextSample(); this.TotalCpuUsage = CounterSample.Calculate(cs1, cs2); this.TotalProcessorCount = Environment.ProcessorCount; }
public static void GetCpuUsage() { PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); CounterSample cs1 = cpuCounter.NextSample(); System.Threading.Thread.Sleep(100); CounterSample cs2 = cpuCounter.NextSample(); float finalCpuCounter = CounterSample.Calculate(cs1, cs2); log.InfoFormat("\tCPU Usage: {0}", finalCpuCounter); }
/// Returns this process's CPU utilization since the last call to ResetCounter(). public float GetCpuUtilization() { if (_cnt == null) { return(float.NaN); } CounterSample curr = _cnt.NextSample(); float cpuutil = CounterSample.Calculate(_prevSample, curr); _prevSample = curr; return(cpuutil); }
/// <summary> /// Print the counters values to the console. /// Should only be called after each thread incrementing the counters has called <see cref="IPerfCountersContainer.Complete"/>. /// </summary> public void PrintCounters() { foreach (var entry in _initialSamples) { var counter = entry.Key; var initialSample = entry.Value; var finalSample = counter.NextSample(); var counterValue = CounterSample.Calculate(initialSample, finalSample); Console.WriteLine("{0,-20} {1,-30}", counter.CounterName, counterValue.ToString("N0")); } }
/// <summary> /// Calculates average performance counters. /// </summary> /// <param name="metricName"> /// Metric name it will be passed to Sentinel /// </param> /// <param name="table"> /// metric table /// </param> /// <param name="moduleName"> /// The key part 1. Module name + the name of metric that is collected /// </param> /// <param name="counterName"> /// The key part 2. Module name + the name of metric that is collected /// </param> /// <param name="collectedSample"> /// performance counter sample /// </param> /// <param name="logger"> /// Logger object /// </param> private void UpdateCounterSamples(string metricName, Dictionary <string, string> table, string moduleName, string counterName, PerfCounterSampleHolder collectedSample, ILog logger) { // As a key for CounterSamples dictionary combination of module name and metric name will be used // (for cases different modules - the same metric name) if (!this.counterSamples.ContainsKey(moduleName + "_" + metricName)) { // checking whether it is first sample logger.DebugFormat("Adding first sample of {0}", moduleName + "_" + counterName); this.counterSamples.Add(moduleName + "_" + metricName, collectedSample); // holds last sample of relevant perf counter } else { logger.DebugFormat("We already have sample for {0}", moduleName + "_" + metricName); PerfCounterSampleHolder currentSample = this.counterSamples[moduleName + "_" + metricName]; // the smaple was collected and previous polling DateTime checkTime = currentSample.CollectingTime.AddSeconds(currentSample.Interval); // adding collecting period if (checkTime < collectedSample.CollectingTime) { // checking if it is time to culculate the value of average perf counter logger.Debug("It is time to calculate the new perf. counter value."); if (currentSample.Sample.TimeStamp100nSec == collectedSample.Sample.TimeStamp100nSec) { // checking if not the same sample logger.Debug("The sample is the same"); currentSample.TryToWaitDelta(); // waiting delta this.UpdateMetricTableWithExistingValueOrNA(metricName, table, logger); return; } if (!table.ContainsKey(metricName)) { if (!this.averageValues.ContainsKey(metricName)) { this.averageValues.Add(metricName, CounterSample.Calculate(currentSample.Sample, collectedSample.Sample).ToString(CultureInfo.InvariantCulture)); // add value } else { this.averageValues[metricName] = CounterSample.Calculate(currentSample.Sample, collectedSample.Sample).ToString(CultureInfo.InvariantCulture); // update value } logger.DebugFormat("Updating value of counter {0} with new one: {1}", metricName, this.averageValues[metricName]); table.Add(metricName, this.averageValues[metricName]); // add value to resulted table collectedSample.CollectingTime = checkTime; // update time logger.Debug("Updating sample"); this.counterSamples[moduleName + "_" + metricName] = collectedSample; // update sample } } } this.UpdateMetricTableWithExistingValueOrNA(metricName, table, logger); }
public object GetAttribute(string attributeName) { PerformanceCounter counter; if (_counters.TryGetValue(attributeName, out counter)) { return(CounterSample.Calculate(counter.NextSample())); } else { throw new AttributeNotFoundException(attributeName, _thisName, typeof(PerfCounterMBean).AssemblyQualifiedName); } }
public void GetSamples(int waitTime = 1000) { foreach (var item in PerfCounterItems.Values) { item.FirstSample = item.PerfCounter.NextSample(); } Thread.Sleep(waitTime); foreach (var item in PerfCounterItems.Values) { item.LastSample = item.PerfCounter.NextSample(); item.SampleResult = CounterSample.Calculate(item.FirstSample, item.LastSample); } }
public void BuiltInCountersWork() { // --- Act var counter = PmcManager.GetCounter <ProcessorTimePercentagePmc>(); var sample1 = counter.NextSample(); Thread.Sleep(400); var sample2 = counter.NextSample(); var value = CounterSample.Calculate(sample1, sample2); Console.WriteLine(value); // --- Assert value.ShouldBeGreaterThanOrEqualTo(0.0F); }
//constructor public ProcessMonitor() { processes = new List <ProcessObj>(); Process[] allProcesses = Process.GetProcesses(); // array of current proccesses CounterSample[] firstSample = new CounterSample[allProcesses.Length]; CounterSample[] secondSample = new CounterSample[allProcesses.Length]; for (int p = 0; p < allProcesses.Length; p++) { var cpu = new PerformanceCounter("Process", "% Processor Time", allProcesses[p].ProcessName); try { firstSample[p] = cpu.NextSample(); } catch (Exception e) { string s = e.Message; } } Thread.Sleep(300); for (int p = 0; p < allProcesses.Length; p++) { var cpu = new PerformanceCounter("Process", "% Processor Time", allProcesses[p].ProcessName); try { if (allProcesses[p].ProcessName.Contains("GUI")) { secondSample[p] = cpu.NextSample(); var mem = allProcesses[p].WorkingSet64; ProcessObj process = new ProcessObj(allProcesses[p], CounterSample.Calculate(firstSample[p], secondSample[p]) / Environment.ProcessorCount, mem); processes.Add(process); } else { secondSample[p] = cpu.NextSample(); var mem = allProcesses[p].WorkingSet64; ProcessObj process = new ProcessObj(allProcesses[p], CounterSample.Calculate(firstSample[p], secondSample[p]) / Environment.ProcessorCount, mem); processes.Add(process); } } catch (Exception e) { string s = e.Message; } } }
public float GetValue() { if (_lastSample == null) { _lastSample = _performanceCounter.NextSample(); return(_performanceCounter.NextValue()); } CounterSample sample = _performanceCounter.NextSample(); //calculate the difference float value = CounterSample.Calculate(_lastSample, sample); _lastSample = sample; return(value); }
private void Sample(object state) { lock (this.sync) { if (!this.isDisposed) { var startTime = DateTime.Now; CounterSample currentSample = this.counter.NextSample(); float value = CounterSample.Calculate(this.previousSample, currentSample); this.observer.OnNext(new PerformanceCounterSample { StartTime = startTime, Value = value }); this.previousSample = currentSample; this.timer.Change(this.pollingInterval.Milliseconds, -1); } } }
/// <summary> /// Safely gets the next value of a performance counter, by ensuring that a minimum duration has passed since /// the last next value was requested. /// </summary> /// <param name="counter">The counter.</param> /// <returns>System.Single.</returns> public static float SafeNextValue([NotNull] this PerformanceCounter counter) { if (counter == null) { throw new ArgumentNullException("counter"); } LinkedList <CounterSample> samples = _samples.GetOrAdd(counter, c => new LinkedList <CounterSample>()); // ReSharper disable once PossibleNullReferenceException lock (samples) { CounterSample nextSample = counter.NextSample(); CounterSample lastSample = CounterSample.Empty; LinkedListNode <CounterSample> node = samples.Last; while (node != null) { CounterSample sample = node.Value; if (lastSample.TimeStamp == 0) { if (GetElapsedTime(sample, nextSample) >= Duration.FromSeconds(1)) { lastSample = sample; } } else { // This sample is no longer needed. samples.Remove(node); } node = node.Previous; } samples.AddLast(nextSample); if (lastSample.TimeStamp == 0) { // We haven't got a sample that's over a second old, so use the earliest sample we have. if (samples.First == null) { return(0.0f); } lastSample = samples.First.Value; } return(CounterSample.Calculate(lastSample, nextSample)); } }
/// <summary> /// Step 4: Now let us record the sampling data we just collected for this run, and aggregate the results if necessary. /// </summary> public virtual void Record() { long[] bytesPerSec = null; long[] recvsPerSec = null; long[] sendsPerSec = null; foreach (var item in _samples) { var counterName = item.Key.CounterName; var key = String.Format("{0};{1}", ScenarioName, counterName); var samplesList = item.Value; long[] values = new long[samplesList.Count - 1]; for (int i = 0; i < samplesList.Count - 1; i++) { values[i] = (long)Math.Round(CounterSample.Calculate(samplesList[i], samplesList[i + 1])); #if PERFRUN Microsoft.VisualStudio.Diagnostics.Measurement.MeasurementBlock.Mark((ulong)values[i], key); #endif } RecordAggregates(key, values); if (counterName.Contains("Bytes/sec")) { bytesPerSec = values; } else if (counterName.Contains("Received/Sec")) { recvsPerSec = values; } else if (counterName.Contains("Published/Sec")) { sendsPerSec = values; } } if ((bytesPerSec != null) && (recvsPerSec != null) && (sendsPerSec != null)) { var bytesPerMsg = new long[bytesPerSec.Length]; for (int i = 0; i < bytesPerSec.Length; i++) { bytesPerMsg[i] = (long)Math.Round((double)bytesPerSec[i] / (recvsPerSec[i] + sendsPerSec[i])); } RecordAggregates("Allocated Bytes/Message", bytesPerMsg); } }
void Sample(object state) { lock (_sync) { if (!_isDisposed) { DateTime startTime = DateTime.UtcNow; CounterSample currentSample = _counter.NextSample(); float value = CounterSample.Calculate(_previousSample, currentSample); _observer.OnNext(new PerformanceCounterSample { StartTime = startTime, Value = value }); _previousSample = currentSample; _timer.Change(_pollingInterval.Milliseconds, -1); } } }