public ViewModel() { mgt = new ManagementClass("Win32_Processor"); procs = mgt.GetInstances(); CPU = new ObservableCollection<Model>(); timer = new DispatcherTimer(); random = new Random(); time = DateTime.Now; cpuCounter = new PerformanceCounter(); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; ramCounter = new PerformanceCounter("Memory", "Available MBytes"); ProcessorID = GetProcessorID(); processes = Process.GetProcesses(); Processes = processes.Length; MaximumSpeed = GetMaxClockSpeed(); LogicalProcessors = GetNumberOfLogicalProcessors(); Cores = GetNumberOfCores(); L2Cache = GetL2CacheSize(); L3Cache = GetL3CacheSize(); foreach (ManagementObject item in procs) L1Cache = ((UInt32)item.Properties["L2CacheSize"].Value / 2).ToString() + " KB"; timer.Interval = TimeSpan.FromMilliseconds(1000); timer.Tick += timer_Tick; timer.Start(); for (int i = 0; i < 60; i++) { CPU.Add(new Model(time, 0,0)); time = time.AddSeconds(1); } }
public static String GetCounterValue(PerformanceCounter pPerformanceCounter) { String retval = ""; // Retrieve PerformanceCounter result based on its CounterType. switch (pPerformanceCounter.CounterType) { case PerformanceCounterType.NumberOfItems32: retval = pPerformanceCounter.RawValue.ToString(); break; case PerformanceCounterType.NumberOfItems64: retval = pPerformanceCounter.RawValue.ToString(); break; case PerformanceCounterType.RateOfCountsPerSecond32: retval = pPerformanceCounter.NextValue().ToString(); break; case PerformanceCounterType.RateOfCountsPerSecond64: retval = pPerformanceCounter.NextValue().ToString(); break; case PerformanceCounterType.AverageTimer32: retval = pPerformanceCounter.NextValue().ToString(); break; default: retval = null; break; } return retval; }
public PerformanceCounterInfo(string name, PerformanceCounter performanceCounters, string alias, IEnumerable<ITag> tags) { _name = name; _performanceCounters = performanceCounters; _alias = alias; _tags = (tags ?? new List<ITag>()).ToList(); }
public int RAM_Count() { PerformanceCounter perfMemCount = new PerformanceCounter("Memory", "Available MBytes"); perfMemCount.NextValue(); short currentAvailableMemory = (short)perfMemCount.NextValue(); return currentAvailableMemory; }
private void MainWindowLoaded(object sender, RoutedEventArgs e) { //var mCounter = new System.Diagnostics.PerformanceCounter("Processor", @"% Processor Time", @"_Total",true); //var mCounter = new System.Diagnostics.PerformanceCounter("Memory", @"% Processor Time", @"_Total",true); mCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Privileged Time", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Interrupt Time", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("Processor", "% DPC Time", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes", null); //var mCounter = new System.Diagnostics.PerformanceCounter("Memory", "Committed Bytes", null); //var mCounter = new System.Diagnostics.PerformanceCounter("Memory", "Commit Limit", null); //var mCounter = new System.Diagnostics.PerformanceCounter("Memory", "% Committed Bytes In Use", null); //var mCounter = new System.Diagnostics.PerformanceCounter("Memory", "Pool Paged Bytes", null); //var mCounter = new System.Diagnostics.PerformanceCounter("Memory", "Pool Nonpaged Bytes", null); //var mCounter = new System.Diagnostics.PerformanceCounter("Memory", "Cache Bytes", null); //var mCounter = new System.Diagnostics.PerformanceCounter("Paging File", "% Usage", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "Avg. Disk Queue Length", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "Disk Read Bytes/sec", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "Disk Write Bytes/sec", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "Avg. Disk sec/Read", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "Avg. Disk sec/Write", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "% Disk Time", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("Process", "Handle Count", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("Process", "Thread Count", "_Total"); //var mCounter = new System.Diagnostics.PerformanceCounter("System", "Context Switches/sec", null); //var mCounter = new System.Diagnostics.PerformanceCounter("System", "System Calls/sec", null); //var mCounter = new System.Diagnostics.PerformanceCounter("System", "Processor Queue Length", null); InitGraph(); mTimer = new DispatcherTimer(); mTimer.Tick += TimerTick; mTimer.Interval = TimeSpan.FromMilliseconds(1000); mTimer.Start(); }
static void Main(string[] args) { cpuCounter = new PerformanceCounter(); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; ramCounter = new PerformanceCounter("Memory", "Available MBytes"); foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get()) { cores = cores + int.Parse(item["NumberOfCores"].ToString()); } int procCount = System.Environment.ProcessorCount; for (int i = 0; i < procCount; i++) { System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", i.ToString()); cpuCounters.Add(pc); } TotalRAM = RAMCapacity(); #if false Thread c = new Thread(ConsumeCPU); c.IsBackground = true; c.Start(); #endif Thread u = new Thread(Update); u.Start(); Thread b = new Thread(Bar); b.Start(); }
/// <summary> /// Runs a memory monitor /// </summary> /// <param name="stick">The BlinkStick to use</param> /// <param name="keepGoing">A callback method; when this returns false, the loop stops</param> public static void Run(BlinkStick stick, Func<bool> keepGoing) { var bands = new SortedDictionary<float, Color> { { 20f, Color.Blue }, { 50f, Color.Green }, { 70f, Color.Yellow }, { 90f, Color.Orange }, { 100f, Color.Red } }; ulong totalMemoryInBytes = new ComputerInfo().TotalPhysicalMemory; float totalMemoryInMegabytes = (float)((double)totalMemoryInBytes / (1024 * 1024)); using (var pc = new PerformanceCounter("Memory", "Available Mbytes")) { while (keepGoing()) { float memoryUsagePercent = (100 * (totalMemoryInMegabytes - pc.NextValue())) / totalMemoryInMegabytes; stick.WriteLine("memoryUsage = {0}", memoryUsagePercent); stick.LedColor = ColorExtensions.ValueToColor(bands, memoryUsagePercent); Thread.Sleep(1000); } } }
private string GetInstanceName(int processId) { instanceName = ""; if (!string.IsNullOrEmpty(processName)) { Process[] processes = Process.GetProcessesByName(processName); if (processes.Length > 0) { int i = 0; foreach (Process p in processes) { instanceName = FormatInstanceName(p.ProcessName, i); if (PerformanceCounterCategory.CounterExists("ID Process", "Process")) { PerformanceCounter counter = new PerformanceCounter( "Process", "ID Process", instanceName); if (processId == counter.RawValue) { if (common.Debug) common.LogMessage(instanceName + " : " + processId); cpuCounter = new PerformanceCounter("Process", "% Processor Time", instanceName); break; } instanceName = ""; } i++; } } } return instanceName; }
static MachineStatus() { _checkStatus = true; Process = Process.GetCurrentProcess(); string processName = Process.ProcessName; CpuCounter = CpuCounter ?? new PerformanceCounter() { CategoryName = "Processor", CounterName = "% Processor Time", InstanceName = "_Total", }; RamCounter = RamCounter ?? new PerformanceCounter() { CategoryName = "Memory", CounterName = "Available MBytes" }; ProcessCpuCounter = ProcessCpuCounter ?? new PerformanceCounter() { CategoryName = "Process", CounterName = "% Processor Time", InstanceName = processName }; }
private void RegisterPrintSpooler() { string categoryName = "Print Queue"; PerformanceCounterCategory perfCategory = new PerformanceCounterCategory(categoryName); string[] instanceNames = perfCategory.GetInstanceNames().Where(name => name != "_Total").ToArray(); foreach (string instanceName in instanceNames) { foreach (string counterName in new string[] { "Total Jobs Printed", "Jobs", "Job Errors" }) { System.Diagnostics.PerformanceCounter tmpPerfCounter = new System.Diagnostics.PerformanceCounter(); tmpPerfCounter.CategoryName = categoryName; tmpPerfCounter.CounterName = counterName; tmpPerfCounter.InstanceName = instanceName; string metricName = string.Format("perfmon_{0}_{1}_total", categoryName.Replace(" ", "_").ToLower().Trim(), counterName.Replace(" ", "_").ToLower().Trim()); Prometheus.Gauge tmpPrometheusCounter = Metrics.CreateGauge(metricName, "help text", labelNames: new[] { "name" }); CounterEntry entry = new CounterEntry() { PerfCounter = tmpPerfCounter, PrometheusCollector = tmpPrometheusCounter }; this.RegisteredCounts.Add(entry); } } }
public MonitorPerformanceCounter(string Category, string Metric, string Instance = "", string ReportingName = null) { FriendlyName = string.IsNullOrWhiteSpace(ReportingName) ? Metric : ReportingName; _performanceCounter = new System.Diagnostics.PerformanceCounter(Category, Metric, Instance); _performanceCounter.NextValue(); // always grab one sample on creation to ensure validity }
internal static double getMemSize(string svc) { // slow, doesn't work most of the time for wtf reason try { ServiceController service = new ServiceController(svc); string foo = service.ServiceName; System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter(); pc.CategoryName = "Process"; pc.CounterName = "Working Set - Private"; pc.InstanceName = foo; double memsize = (double)(pc.NextValue() / 1024 / 1024); // mb //Process[] localByName = Process.GetProcessesByName(svc); //foreach (Process p in localByName) //{ // //Console.WriteLine("Private memory size64: {0}", (p.PrivateMemorySize64 / f).ToString("#,##0")); // memsize += p.WorkingSet64 / 1024/ 1024; // //Console.WriteLine("Peak virtual memory size64: {0}", (p.PeakVirtualMemorySize64 / f).ToString("#,##0")); // //Console.WriteLine("Peak paged memory size64: {0}", (p.PeakPagedMemorySize64 / f).ToString("#,##0")); // //Console.WriteLine("Paged system memory size64: {0}", (p.PagedSystemMemorySize64 / f).ToString("#,##0")); // //Console.WriteLine("Paged memory size64: {0}", (p.PagedMemorySize64 / f).ToString("#,##0")); // //Console.WriteLine("Nonpaged system memory size64: {0}", (p.NonpagedSystemMemorySize64 / f).ToString("#,##0")); //} return(Math.Round(memsize, 2)); } catch { return(-1); } }
public void ProcedureFromCache() { return; if (Version < new Version(5, 0)) return; execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL("CREATE PROCEDURE spTest(id int) BEGIN END"); PerformanceCounter hardQuery = new PerformanceCounter( ".NET Data Provider for MySQL", "HardProcedureQueries", true); PerformanceCounter softQuery = new PerformanceCounter( ".NET Data Provider for MySQL", "SoftProcedureQueries", true); long hardCount = hardQuery.RawValue; long softCount = softQuery.RawValue; MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?id", 1); cmd.ExecuteScalar(); Assert.AreEqual(hardCount + 1, hardQuery.RawValue); Assert.AreEqual(softCount, softQuery.RawValue); hardCount = hardQuery.RawValue; MySqlCommand cmd2 = new MySqlCommand("spTest", conn); cmd2.CommandType = CommandType.StoredProcedure; cmd2.Parameters.AddWithValue("?id", 1); cmd2.ExecuteScalar(); Assert.AreEqual(hardCount, hardQuery.RawValue); Assert.AreEqual(softCount + 1, softQuery.RawValue); }
public int Ram() { PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes"); int ram = Convert.ToInt32(ramCounter.NextValue()); return ram; }
internal SenderInstrumentationPublisher(string instanceName, SenderInstrumentationManager instrumentationManager) { _totalMessagesSentCounter = instrumentationManager.TotalMessagesSentCounterDefinition.CreatePerformanceCounter(instanceName); _totalMessagesRequestedCounter = instrumentationManager.TotalMessagesRequestedCounterDefinition.CreatePerformanceCounter(instanceName); _messagesSentPerSecondCounter = instrumentationManager.MessagesSentPerSecondCounterDefinition.CreatePerformanceCounter(instanceName); _messagesRequestedPerSecondCounter = instrumentationManager.MessagesRequestedPerSecondCounterDefinition.CreatePerformanceCounter(instanceName); _totalBytesSentCounter = instrumentationManager.TotalBytesSentCounterDefinition.CreatePerformanceCounter(instanceName); _bytesPerSecondSentCounter = instrumentationManager.BytesSentPerSecondCounterDefinition.CreatePerformanceCounter(instanceName); _averageMessageSendingTimeCounter = instrumentationManager.AverageMessageSendingTimeCounterDefinition.CreatePerformanceCounter(instanceName); _averageMessageSendingTimeBaseCounter = instrumentationManager.AverageMessageSendingTimeBaseCounterDefinition.CreatePerformanceCounter(instanceName); _totalMessagesSentCounter.RawValue = 0L; _totalMessagesRequestedCounter.RawValue = 0L; _totalBytesSentCounter.RawValue = 0L; _averageMessageSendingTimeCounter.RawValue = 0L; _averageMessageSendingTimeBaseCounter.RawValue = 0L; }
static bool TryToInstantiatePerformanceCounter(string counterName, string instanceName, out PerformanceCounter counter, bool throwIfFails) { if (instanceName.Length > 128) { throw new Exception(string.Format("The endpoint name ('{0}') is too long (longer then {1}) to register as a performance counter instance name. Please reduce the endpoint name.", instanceName, (int)SByte.MaxValue)); } var message = String.Format("NServiceBus performance counter for '{0}' is not set up correctly. To rectify this problem see http://docs.particular.net/search?q=PerformanceCounters.", counterName); try { counter = new PerformanceCounter("NServiceBus", counterName, instanceName, false); } catch (Exception ex) { if (throwIfFails) { throw new InvalidOperationException(message, ex); } logger.Info(message); counter = null; return false; } return true; }
public static PerformanceCounter Get(string counter, string instance) { var key = counter + " - " + instance; lock (counters) if (!counters.ContainsKey(key)) { RegisterAll(); var performanceCounter = new PerformanceCounter { CategoryName = CategoryName, CounterName = counter, InstanceName = instance, ReadOnly = false, InstanceLifetime = PerformanceCounterInstanceLifetime.Process }; performanceCounter.RawValue = 0; counters.Add(key, performanceCounter); } return counters[key]; }
public InstancePerformanceCounter(string name, string categoryName, string instanceName) { _performanceCounter = new PerformanceCounter(categoryName, name, instanceName, false) { RawValue = 0 }; }
private void TryToInitializeCounters() { if (!countersInitialized) { PerformanceCounterCategory category = new PerformanceCounterCategory(".NET CLR Networking 4.0.0.0"); var instanceNames = category.GetInstanceNames().Where(i => i.Contains(string.Format("p{0}", pid))); if (instanceNames.Any()) { bytesSentPerformanceCounter = new PerformanceCounter(); bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0"; bytesSentPerformanceCounter.CounterName = "Bytes Sent"; bytesSentPerformanceCounter.InstanceName = instanceNames.First(); bytesSentPerformanceCounter.ReadOnly = true; bytesReceivedPerformanceCounter = new PerformanceCounter(); bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0"; bytesReceivedPerformanceCounter.CounterName = "Bytes Received"; bytesReceivedPerformanceCounter.InstanceName = instanceNames.First(); bytesReceivedPerformanceCounter.ReadOnly = true; countersInitialized = true; } } }
public CpuPerformanceReader() { _cpuCounter = new PerformanceCounter(); _cpuCounter.CategoryName = "Processor"; _cpuCounter.CounterName = "% Processor Time"; _cpuCounter.InstanceName = "_Total"; }
public MainForm() { InitializeComponent(); if (!string.IsNullOrEmpty(Program.directory)) { this.Text += "-[" + Program.directory + "]"; } #if DEBUG diskSpaceCheckTimer.Interval = 1000 * 60; #endif config.GetLineCameras(); Properties.Settings setting = Properties.Settings.Default; cpuCounter = new PerformanceCounter(); ramCounter = new PerformanceCounter("Memory", "Available MBytes"); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; time = new System.Windows.Forms.Timer(); time.Tick += time_Elapsed; time.Interval = 3000; time.Enabled = true; InitStatusBar(); }
public float CollectMetric(PluginResource pluginResource, string option = null) { // get a handle on the service first var service = ServiceController.GetServices().FirstOrDefault(s => s.DisplayName == option); if (service == null) { throw new Exception(string.Format("Windows service by name '{0}' not found", option)); } if (service.Status == ServiceControllerStatus.Stopped) { return default(float); } else if (pluginResource.ResourceTextKey == StatusResource) { return 1; } // get a handle on the process var serviceMgtObj = new ManagementObject(@"Win32_Service.Name='" + service.ServiceName + "'"); var serviceProcess = Process.GetProcessById(Convert.ToInt32(serviceMgtObj["ProcessId"])); // return perfomance counter value for process var perfCounter = new PerformanceCounter("Process", pluginResource.Label, serviceProcess.ProcessName); var value = perfCounter.NextValue(); if (value == 0.0) { Thread.Sleep(1000); value = perfCounter.NextValue(); } return value; }
// Token: 0x06001813 RID: 6163 // RVA: 0x00074C64 File Offset: 0x00072E64 public STPInstancePerformanceCounter(string string_0, STPPerformanceCounterType stpperformanceCounterType_0) : this() { STPPerformanceCounters instance = STPPerformanceCounters.Instance; this._pcs = new PerformanceCounter("SmartThreadPool", instance._stpPerformanceCounters[(int)stpperformanceCounterType_0].Name, string_0, false); this._pcs.RawValue = this._pcs.RawValue; }
/// <summary> /// Sample all defined counters. /// </summary> public void SampleCounters() { lock (m_counters) { #if !MONO // Sample custom thread pool counters (these already exist in Mono) PerformanceCounter workerThreadsCounter = FindCounter(ThreadPoolCountersCategoryName, "Worker Threads"); PerformanceCounter completionPortThreadsCounter = FindCounter(ThreadPoolCountersCategoryName, "Completion Port Threads"); if ((object)workerThreadsCounter != null && (object)completionPortThreadsCounter != null) { System.Diagnostics.PerformanceCounter workerThreads = workerThreadsCounter.BaseCounter; System.Diagnostics.PerformanceCounter completionPortThreads = completionPortThreadsCounter.BaseCounter; if ((object)workerThreads != null && (object)completionPortThreads != null) { int maximumWorkerThreads, maximumCompletionPortThreads, availableWorkerThreads, availableCompletionPortThreads; ThreadPool.GetMaxThreads(out maximumWorkerThreads, out maximumCompletionPortThreads); ThreadPool.GetAvailableThreads(out availableWorkerThreads, out availableCompletionPortThreads); workerThreads.RawValue = maximumWorkerThreads - availableWorkerThreads; completionPortThreads.RawValue = maximumCompletionPortThreads - availableCompletionPortThreads; } } #endif foreach (PerformanceCounter counter in m_counters) { counter.Sample(); } } }
public void IncrementCounterBy(string counter, int amount) { if (String.IsNullOrEmpty(_category)) { _category = ResourceContainer.Configuration.ReadValue("diagnostics", "performance-counters-category"); _enabled = (ResourceContainer.Configuration.ReadValue("diagnostics", "performance-counters-enabled").ToLower() == "true"); } // if we're not enabled, just exit if (!_enabled) { return; } // checked if the counter is cached if (!_counterCache.ContainsKey(counter)) { // create the counter if it didn't exist if (!PerformanceCounterCategory.Exists(_category) || !PerformanceCounterCategory.CounterExists(counter, _category)) { CreateCounter(counter); } if (!_enabled) { return; } // cache the counter PerformanceCounter performanceCounter = new PerformanceCounter(_category, counter, false); _counterCache.Add(counter, performanceCounter); } // increment the counter _counterCache[counter].IncrementBy(amount); }
public EnterpriseLibraryPerformanceCounter CreateCounter(string categoryName, string counterName, string[] instanceNames) { if (instanceNames == null) throw new ArgumentNullException("instanceNames"); string combinedCounterNameRoot = categoryName.ToLowerInvariant() + counterName.ToLowerInvariant(); PerformanceCounter[] counters = new PerformanceCounter[instanceNames.Length]; for (int i = 0; i < instanceNames.Length; i++) { string combinedCounterName = combinedCounterNameRoot + instanceNames[i].ToLowerInvariant(); lock (lockObject) { if (counterCache.ContainsKey(combinedCounterName) == false) { PerformanceCounter newCounter = new PerformanceCounter(categoryName, counterName, instanceNames[i], false); counterCache.Add(combinedCounterName, newCounter); } counters[i] = counterCache[combinedCounterName]; } } return new EnterpriseLibraryPerformanceCounter(counters); }
public ActionResult ImportExcel() { var httpFileCollection = Request.Files["file"]; if (httpFileCollection.ContentLength > 0) { string extension = System.IO.Path.GetExtension(httpFileCollection.FileName).ToLower(); string path = string.Format("{0}/{1}", Server.MapPath("~/ExcelData/Uploads"), Request.Files["file"].FileName); if (!Directory.Exists(path)) // if upload folder path does not exist, create one. { Directory.CreateDirectory(Server.MapPath("~/ExcelData/Uploads")); } string[] validFileTypes = { ".xls", ".xlsx", ".csv" }; if (validFileTypes.Contains(extension)) { if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); // if file exist previously, delete previous one } httpFileCollection.SaveAs(path); var performance = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes"); Console.WriteLine(performance.NextValue()); XslLibrary.ReadDataTable(path); Console.WriteLine(performance.NextValue()); XslLibrary.ImportFromExcelNpoi(path); Console.WriteLine(performance.NextValue()); } } TempData["Success"] = "Success"; return(new ContentResult()); }
private IEnumerable<Process> GetProcessAndParent() { var currentProcess = Process.GetCurrentProcess(); var pc = new PerformanceCounter("Process", "Creating Process Id", currentProcess.ProcessName); var parentProcess = Process.GetProcessById((int)pc.RawValue); return new[] { currentProcess, parentProcess }; }
internal void PerformanceCollectorBadStateTest(IPerformanceCollector collector) { var counters = new PerformanceCounter[] { new PerformanceCounter("Processor", "% Processor Time", "_Total123blabla"), new PerformanceCounter("Processor", "% Processor Time", "_Total") }; foreach (var pc in counters) { try { string error = null; collector.RegisterCounter( PerformanceCounterUtility.FormatPerformanceCounter(pc), null, true, out error, false); } catch (Exception) { } } Assert.IsTrue(collector.PerformanceCounters.First().IsInBadState); Assert.IsFalse(collector.PerformanceCounters.Last().IsInBadState); }
internal GPGPUProperties(bool simulate = false, bool useAdvanced = true) { IsSimulated = simulate; Message = string.Empty; UseAdvanced = useAdvanced; MultiProcessorCount = 0; HighPerformanceDriver = false; SupportsDoublePrecision = true; AsynchEngineCount = 1; if (simulate) { Capability = new Version(0, 0); Name = "Simulator"; DeviceId = 0; ulong freeMem = Int32.MaxValue; try { PerformanceCounter pc = new PerformanceCounter("Memory", "Available Bytes"); freeMem = Convert.ToUInt64(pc.NextValue()); } catch (Exception ex) { Debug.WriteLine(ex.Message); #if DEBUG throw; #endif } TotalMemory = freeMem; MaxGridSize = new dim3(65536, 65536); MaxThreadsSize = new dim3(1024, 1024); MaxThreadsPerBlock = 1024; } }
internal void PerformanceCollectorRefreshCountersTest(IPerformanceCollector collector) { var counters = new PerformanceCounter[] { new PerformanceCounter("Processor", "% Processor Time", "_Total123blabla"), new PerformanceCounter("Processor", "% Processor Time", "_Total"), new PerformanceCounter("Processor", "% Processor Time", "_Total123afadfdsdf"), }; foreach (var pc in counters) { try { string error = null; collector.RegisterCounter( PerformanceCounterUtility.FormatPerformanceCounter(pc), null, true, out error, false); } catch (Exception) { } } collector.RefreshCounters(); // All bad state counters are removed and added later through register counter, and as a result, the order of the performance coutners is changed. Assert.AreEqual(collector.PerformanceCounters.First().InstanceName, "_Total"); Assert.AreEqual(collector.PerformanceCounters.Last().InstanceName, "_Total123afadfdsdf"); }
public void BothCounters() { using (XmlSerializerCache cache = new XmlSerializerCache()) { string instanceName = PerfCounterManagerTests.GetCounterInstanceName(0); using (PerformanceCounter instanceCounter = new PerformanceCounter(PerfCounterManagerTests.CATEGORY , PerfCounterManagerTests.CACHED_INSTANCES_NAME , instanceName , true)) { Assert.AreEqual(0, instanceCounter.RawValue); using (PerformanceCounter hitCounter = new PerformanceCounter(PerfCounterManagerTests.CATEGORY , PerfCounterManagerTests.SERIALIZER_HITS_NAME , instanceName , true)) { Assert.AreEqual(0, hitCounter.RawValue); XmlRootAttribute root = new XmlRootAttribute( "theRoot" ); XmlSerializer ser = cache.GetSerializer(typeof(SerializeMe), root); Assert.AreEqual(1, instanceCounter.RawValue); Assert.AreEqual(0, hitCounter.RawValue); ser = cache.GetSerializer(typeof(SerializeMe), root); Assert.AreEqual(1, instanceCounter.RawValue); Assert.AreEqual(1, hitCounter.RawValue); } } } }
public void Render() { int count = 0; using (var processRam = new PerformanceCounter("Process", "Working Set", Process.GetCurrentProcess().ProcessName)) { var sw = new Stopwatch(); sw.Start(); while (sw.ElapsedMilliseconds < 10000) { long duration = sw.ElapsedMilliseconds; _testable.Render(); count++; Logger.Instance.Info(new Statistics { Memory = processRam.RawValue/1024, Duration = duration, Description = "Frame", FramePerSecond = count/sw.Elapsed.TotalSeconds }); } Logger.Instance.Info(new Statistics { Memory = processRam.RawValue/1024, Duration = 10000, FramePerSecond = count/sw.Elapsed.TotalSeconds, Description = "Summary" }); sw.Stop(); } }
private static bool IsNotCounterBase(PerformanceCounter p) { return p.CounterType != PerformanceCounterType.AverageBase && p.CounterType != PerformanceCounterType.CounterMultiBase && p.CounterType != PerformanceCounterType.RawBase && p.CounterType != PerformanceCounterType.SampleBase; }
static void Main(string[] args) { var metricPrefix = "one_sec.monitor"; if (args.Length > 0) { metricPrefix = args[0]; } AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; StaticMetricsPipeProvider.Instance.Start(); var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); var memCounter = new PerformanceCounter("Memory", "Available MBytes"); var cpu = 0; var memory = 0; while (true) { Thread.Sleep(1000); cpu = (int)cpuCounter.NextValue(); memory = (int) memCounter.NextValue(); try { StaticMetricsPipeProvider.Instance.Current.Raw(string.Format("{0}.cpu", metricPrefix), cpu); StaticMetricsPipeProvider.Instance.Current.Raw(string.Format("{0}.free_memory", metricPrefix), memory); } catch (Exception) { } } }
public void buildTrie() { //performance counter to measure available memory PerformanceCounter cpu = new PerformanceCounter("Memory", "Available MBytes"); trie = new Trie(); int counter = 0; //reads the temporary file using (var fileStream = System.IO.File.OpenRead(filepath)) { using (StreamReader reader = new StreamReader(fileStream)) { while (!reader.EndOfStream) { //checks memory every 500 iterations if (counter % 500 == 0) { //if the amount of memory is less than defined amount, end if (cpu.NextValue() < minMemory) { return; } } counter++; //adds to the trie trie.add(reader.ReadLine().Replace("_", " ")); } } } }
public PerformanceCounters(string instance) { try { var perfCollectorModule = new PerformanceCollectorModule(); foreach (var p in typeof(PerformanceCounters).GetProperties()) { var counter = new PerformanceCounter(category, p.Name, instance, false); p.SetValue(this, counter); counter.RawValue = 0; if (!p.Name.EndsWith("Base", StringComparison.Ordinal)) { var perfCounterSpec = $"\\{category}({instance})\\{p.Name}"; var reportAs = p.Name .Replace('_', ' ') .Replace("Per", "/"); perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(perfCounterSpec, reportAs)); } } perfCollectorModule.Initialize(TelemetryConfiguration.Active); } catch (Exception e) { new TelemetryClient().TrackException(e); } }
private void InitializeComponent() { this.performanceCounterBytesSentTotal = new System.Diagnostics.PerformanceCounter(); this.performanceCounterBytesSentPerSec = new System.Diagnostics.PerformanceCounter(); this.performanceCounterRequestsTotal = new System.Diagnostics.PerformanceCounter(); this.performanceCounterRequestsPerSec = new System.Diagnostics.PerformanceCounter(); this.eventLog = new System.Diagnostics.EventLog(); this.timer = new System.Timers.Timer(); ((System.ComponentModel.ISupportInitialize)(this.performanceCounterBytesSentTotal)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.performanceCounterBytesSentPerSec)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.performanceCounterRequestsTotal)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.performanceCounterRequestsPerSec)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.eventLog)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.timer)).BeginInit(); // // performanceCounterBytesSentTotal // this.performanceCounterBytesSentTotal.CategoryName = "Quote Service Counts"; this.performanceCounterBytesSentTotal.CounterName = "# of Bytes sent"; this.performanceCounterBytesSentTotal.ReadOnly = false; // // performanceCounterBytesSentPerSec // this.performanceCounterBytesSentPerSec.CategoryName = "Quote Service Counts"; this.performanceCounterBytesSentPerSec.CounterName = "# of Bytes sent / sec"; this.performanceCounterBytesSentPerSec.ReadOnly = false; // // performanceCounterRequestsTotal // this.performanceCounterRequestsTotal.CategoryName = "Quote Service Counts"; this.performanceCounterRequestsTotal.CounterName = "# of Requests"; this.performanceCounterRequestsTotal.ReadOnly = false; // // performanceCounterRequestsPerSec // this.performanceCounterRequestsPerSec.CategoryName = "Quote Service Counts"; this.performanceCounterRequestsPerSec.CounterName = "# of Requests / sec"; this.performanceCounterRequestsPerSec.ReadOnly = false; // // eventLog // this.eventLog.Log = "Application"; this.eventLog.Source = "QuoteService"; // // timer // this.timer.Enabled = true; this.timer.Interval = 1000; this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer); ((System.ComponentModel.ISupportInitialize)(this.performanceCounterBytesSentTotal)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.performanceCounterBytesSentPerSec)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.performanceCounterRequestsTotal)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.performanceCounterRequestsPerSec)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.eventLog)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.timer)).EndInit(); }
public static long SessionCount(string CategoryName, string CounterName, string InstanceName) { PerformanceCounter performanceCounter = new System.Diagnostics.PerformanceCounter(); performanceCounter.CategoryName = "Web Service"; performanceCounter.CounterName = "Current Connections"; performanceCounter.InstanceName = "LicenKey"; return(performanceCounter.RawValue); }
public ConnectionPoolPerformanceCounter() { PerformanceCounter.CloseSharedResources(); string instance = AppDomain.CurrentDomain.FriendlyName.Split('.').First() + "[" + Process.GetCurrentProcess().Id + "]"; _pooledCounter = new System.Diagnostics.PerformanceCounter(_category, _pooledCounterName, instance, true); _activeCounter = new System.Diagnostics.PerformanceCounter(_category, _activeCounterName, instance, true); _freeCounter = new System.Diagnostics.PerformanceCounter(_category, _freeCounterName, instance, true); }
//============================================================================== Constructors internal PerformanceCounter(System.Diagnostics.PerformanceCounter counter) { if (counter == null) { throw new ArgumentNullException("counter"); } _counter = counter; _counter.ReadOnly = false; Accessible = true; }
void Init() { cpuCounter = new System.Diagnostics.PerformanceCounter(); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes"); //FillAboutPanel(); }
public float GetValue(PerformanceCounter item) { var counter = new System.Diagnostics.PerformanceCounter { CategoryName = item.CategoryName, CounterName = item.CounterName, InstanceName = item.InstanceName, MachineName = item.MachineName }; return(counter.NextValue()); }
protected void CreateCounters() { framesCounter = GetCounter("frames rendered"); packetsSentCounter = GetCounter("packets sent"); packetsReceivedCounter = GetCounter("packets received"); bytesSentCounter = GetCounter("bytes sent"); bytesReceivedCounter = GetCounter("bytes received"); worldCounterTimer = GetCounter("world manager"); networkCounterTimer = GetCounter("network manager"); inputCounterTimer = GetCounter("input handler"); interFrameCounterTimer = GetCounter("inter frame"); renderQueueCounterTimer = GetCounter("render main queue"); }
protected void CreateCounters() { // Sphere tree counters nodeCounter = GetCounter("node count"); shapesAddedCounter = GetCounter("nodes added"); shapesRemovedCounter = GetCounter("nodes removed"); intersectingShapeCounter = GetCounter("intersecting shapes"); topLevelCallsCounter = GetCounter("top-level calls"); partCallsCounter = GetCounter("part calls"); topLevelCollisionsCounter = GetCounter("collisions"); collisionTestCounter = GetCounter("collision tests"); }
public static int GetCpuValue() { //categories similar to the existnig ones in perfmon.exe (windows) var CpuCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total"); //skipping first sample CpuCounter.NextValue(); System.Threading.Thread.Sleep(1000); //recording sample between two different time stamps int gapValue = (int)CpuCounter.NextValue(); return(gapValue); }
public static void GetStatus(Process process, string exename) { 프로세스_CPU_사용량 = 0.0f; 전체_CPU_사용량 = 0.0f; 메모리_사용량 = 0; if (process != null) { 프로세스_CPU_사용량 = GetUsage(process, out 전체_CPU_사용량); var objMemory = new System.Diagnostics.PerformanceCounter("Process", "Working Set - Private", exename); 메모리_사용량 = (int)objMemory.NextValue() / 1000000; } }
private System.Diagnostics.PerformanceCounter GetCounter(string categoryName, string instanceName, string counterName) { var counter = new System.Diagnostics.PerformanceCounter { CategoryName = categoryName, CounterName = counterName, InstanceName = instanceName, ReadOnly = false, InstanceLifetime = PerformanceCounterInstanceLifetime.Process, }; counter.RawValue = 0; return(counter); }
public int GetCpuUsage(string machineName) { if (string.IsNullOrWhiteSpace(machineName)) { machineName = "localhost"; } var counter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", machineName); counter.NextValue(); Thread.Sleep(1000); return((int)counter.NextValue()); }
public async Task <int> GetCpuUsageAsync(string machineName) { if (string.IsNullOrWhiteSpace(machineName)) { machineName = "."; } var counter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", machineName); counter.NextValue(); await Task.Delay(1000).ConfigureAwait(false); return((int)counter.NextValue()); }
private Logger() { _cpuCounter = new System.Diagnostics.PerformanceCounter( "Processor", "% Processor Time", "_Total", true); _ramCounter = new System.Diagnostics.PerformanceCounter( "Memory", "Available MBytes", true); _currentProcess = System.Diagnostics.Process.GetCurrentProcess(); }
public HowTo() { Window1.singleton.MenuToggleButton.IsEnabled = false; Window1.singleton.popupbox.IsEnabled = false; Window1.singleton.homeButton.IsEnabled = false; InitializeComponent(); var ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes", true); Application.Current.Dispatcher.Invoke(new Action(() => { freeram.Content = Convert.ToInt32(ramCounter.NextValue() / 1024).ToString() + "GB"; })); sw.Start(); sw.Elapsed += new ElapsedEventHandler(sw_Tick); sw.Interval = 2000; // in miliseconds }
private void GetUserOnlineCount() { try { string applicationIntanceName = System.Web.Hosting.HostingEnvironment.ApplicationID.Replace('/', '_'); System.Diagnostics.PerformanceCounter performanceCounter = new System.Diagnostics.PerformanceCounter("ASP.NET Applications", "Sessions Active", applicationIntanceName); lblUserOnlineCount_LocalDateTime.Text = GetLocalResourceObject("UserOnlineLabel") + performanceCounter.NextValue().ToString() + " " + GetLocalResourceObject("PersonLabel"); } catch (Exception) { } //if (Application["UserOnlineCount"] != null) //{ // lblUserOnlineCount_LocalDateTime.Text = "کاربران آنلاین :" + Application["UserOnlineCount"].ToString() + " نفر"; //} }
/*Summary * This method is used to do the initialization for detecting the CPU load */ private void InitializePeformanceMonitor() { // This isn't allowed in Vista. if (bVista) { return; } CpuCounter = new System.Diagnostics.PerformanceCounter(); ((System.ComponentModel.ISupportInitialize)(CpuCounter)).BeginInit(); CpuCounter.CategoryName = "Processor"; CpuCounter.CounterName = "% Processor Time"; CpuCounter.InstanceName = "_Total"; ((System.ComponentModel.ISupportInitialize)(CpuCounter)).EndInit(); }
static void initPerformanceCounters() { if (performanceCounter == null) { performanceCounter = new System.Diagnostics.PerformanceCounter(); performanceCounter.CategoryName = "Process"; performanceCounter.CounterName = "Private Bytes"; if (engineLoadingMode == EngineLoadingMode.LoadAsWorkprocess) { performanceCounter.InstanceName = "FCEngine"; } else { performanceCounter.InstanceName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; } } }
}//public static void MemoryManagement() ///<summary>MemoryPerformanceCounter()</summary> public static void MemoryPerformanceCounter() { System.Diagnostics.PerformanceCounter performanceCounter; try { performanceCounter = new System.Diagnostics.PerformanceCounter(); performanceCounter.CategoryName = "Memory"; performanceCounter.CounterName = "System Code Total Bytes"; System.Console.WriteLine( "Memory System Code Total Bytes: {0}", performanceCounter.RawValue.ToString() ); performanceCounter.CounterName = "Available MBytes"; System.Console.WriteLine( "Memory Available MBytes: {0}", performanceCounter.RawValue.ToString() ); }//try catch ( Exception exception ) { System.Console.WriteLine("Exception: {0}", exception.Message ); }//catch ( Exception exception ) }//public static void MemoryPerformanceCounter()
private void ScanMarketEvent(int si, System.Diagnostics.PerformanceCounter performanceCounter) { // 可以讀到正確的值 //Console.Write(string.Format("{0} ", si)); try { if (performanceCounter == null) { return; } int val = (int)performanceCounter.NextValue(); SetChart(si, val); } catch (Exception ex) { MessageBox.Show("Error! " + ex.Message); Debug.WriteLine(ex.Message); } }
public void Run() { // // To get POS.exe stats // fnGetPOSProcessInfo GetPOSProcessInfo = new fnGetPOSProcessInfo(); // GetPOSProcessInfo.Run(); // // These global variables are returned // public static int POSHandleCount = 0; // public static int POSThreads = 0; // public static int POSUsedMemory = 0; // public static int POSGDIObjects = 0; // public static int POSUserObjects = 0; // public static int POSCurrentCPUUsage = 0; // if (Global.RegisterRunningRetech) ProcessName = "source"; // if (Global.RegisterRunningIPOS) ProcessName = "pos"; // if (Global.RegisterRunningIPOS & Global.CurrentScenario <= 30) // ProcessName = "pos"; // // if (Global.RegisterRunningRetech & Global.CurrentScenario > 30) // ProcessName = "source"; System.Diagnostics.Process [] localByName = System.Diagnostics.Process.GetProcessesByName(Global.ProcessName); IntPtr POSHandlePtr = localByName[0].Handle; Global.POSHandleCount = localByName[0].HandleCount; Global.POSThreads = localByName[0].Threads.Count; Global.POSUsedMemory = (int)localByName[0].WorkingSet64 / (1024 * 1024); Global.POSGDIObjects = (int)GetGuiResources(localByName[0].Handle, 0); // GDI Global.POSUserObjects = (int)GetGuiResources(localByName[0].Handle, 1); // User // Get Current Cpu Usage System.Diagnostics.PerformanceCounter CPUUsage; CPUUsage = new System.Diagnostics.PerformanceCounter(); CPUUsage.CategoryName = "Processor"; CPUUsage.CounterName = "% Processor Time"; CPUUsage.InstanceName = "_Total"; CPUUsage.NextValue(); System.Threading.Thread.Sleep(1000); Global.POSCurrentCPUUsage = (int)CPUUsage.NextValue(); }
//================================================================================= Instance methods private void Initialize() { _cpuUsage = 0; try { _cpuCounter = new System.Diagnostics.PerformanceCounter { CategoryName = "Processor", CounterName = "% Processor Time", InstanceName = "_Total" }; _perfCounterTimer = new System.Timers.Timer(3000); _perfCounterTimer.Elapsed += PerfCounter_Timer_Elapsed; _perfCounterTimer.Disposed += PerfCounter_Timer_Disposed; _perfCounterTimer.Enabled = true; } catch (Exception ex) { Logger.WriteWarning(EventId.PerformanceCounters.InitializeFailed, "Performance counter for CPU usage could not be initialized, the value will always be 0. Message: " + ex.Message); } _invalidCounters = new Dictionary <string, bool>(); if (!RepositoryConfiguration.PerformanceCountersEnabled) { _counters = new PerformanceCounter[0]; return; } try { Category = CreateCategory(); _counters = Category.GetCounters().Select(pc => new PerformanceCounter(pc)).ToArray(); } catch (Exception ex) { Logger.WriteException(new Exception("Error during performance counter initialization.", ex)); _counters = new PerformanceCounter[0]; } }
private void NetInterfacePerfMonitor_Load(object sender, EventArgs e) { ShowInterfaceSpeedAndQueue(); int kk = 0; PerformanceCounterCategory categoryInstance = new PerformanceCounterCategory("Network Interface"); foreach (string strInstanceName in categoryInstance.GetInstanceNames()) { System.Windows.Forms.Application.DoEvents(); NetInterfaceChart.Series.Add(strInstanceName); NetInterfaceChart.Series[strInstanceName].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline; NetInterfaceChart.Series[strInstanceName].YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Primary; NetInterfaceChart.Series[strInstanceName].YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32; NetInterfaceChart.Series[strInstanceName].IsXValueIndexed = false; //NetInterfaceChart.Series[strInstanceName].IsValueShownAsLabel = false; //NetInterfaceChart.Series[strInstanceName].IsVisibleInLegend = false; kk++; } NetInterfaceChart.ResetAutoValues(); NetInterfaceChart.ChartAreas[0].AxisY.Maximum = 1024 * 1000;//Max Y NetInterfaceChart.ChartAreas[0].AxisY.Minimum = 0; NetInterfaceChart.ChartAreas[0].AxisX.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.False; System.Timers.Timer[] scanLiveTimer = new System.Timers.Timer[kk]; performanceCounter = new PerformanceCounter[kk]; Netname = new String[kk]; for (int i = 0; i < kk; i++) { Netname[i] = NetInterfaceChart.Series[i].Name.ToString(); performanceCounter[i] = new System.Diagnostics.PerformanceCounter(); performanceCounter[i].MachineName = Dns.GetHostName(); performanceCounter[i].CategoryName = "Network Interface"; performanceCounter[i].CounterName = "Bytes Total/sec"; performanceCounter[i].BeginInit(); performanceCounter[i].InstanceName = Netname[i]; scanLiveTimer[i] = new System.Timers.Timer(); int x = i; System.Diagnostics.PerformanceCounter performanceCounterx = performanceCounter[i]; scanLiveTimer[i].Elapsed += new System.Timers.ElapsedEventHandler((senderx, ex) => ScanMarketEvent(x, performanceCounterx)); scanLiveTimer[i].Interval = 1000; scanLiveTimer[i].Start(); } }