• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Diagnostics.PerformanceCounter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Diagnostics.PerformanceCounter的典型用法代码示例。如果您正苦于以下问题:C# PerformanceCounter类的具体用法?C# PerformanceCounter怎么用?C# PerformanceCounter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



PerformanceCounter类属于System.Diagnostics命名空间,在下文中一共展示了PerformanceCounter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: RAM_Count

 public int RAM_Count()
 {
     PerformanceCounter perfMemCount = new PerformanceCounter("Memory", "Available MBytes");
     perfMemCount.NextValue();
     short currentAvailableMemory = (short)perfMemCount.NextValue();
     return currentAvailableMemory;
 }
开发者ID:MrPlayer141,项目名称:Jarvis,代码行数:7,代码来源:SyS_Counter.cs


示例2: PerformanceCounterInfo

 public PerformanceCounterInfo(string name, PerformanceCounter performanceCounters, string alias, IEnumerable<ITag> tags)
 {
     _name = name;
     _performanceCounters = performanceCounters;
     _alias = alias;
     _tags = (tags ?? new List<ITag>()).ToList();
 }
开发者ID:dowc,项目名称:Influx-Capacitor,代码行数:7,代码来源:PerformanceCounterInfo.cs


示例3: GetCounterValue

        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;
        }
开发者ID:tapman,项目名称:ipc-queue,代码行数:34,代码来源:UTCutil.cs


示例4: ViewModel

        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);
            }
        }
开发者ID:jcw-,项目名称:sparrowtoolkit,代码行数:34,代码来源:ViewModel.cs


示例5: PerformanceCollectorRefreshCountersTest

        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");
        }
开发者ID:Microsoft,项目名称:ApplicationInsights-dotnet-server,代码行数:32,代码来源:PerformanceCollectorTestBase.cs


示例6: IncrementCounterBy

        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);
        }
开发者ID:rev2004,项目名称:certitude,代码行数:30,代码来源:MonitorProvider.cs


示例7: Main

        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)
                {
                }
            }

        }
开发者ID:SyncCloud,项目名称:synccloud.load.poligon,代码行数:30,代码来源:Program.cs


示例8: ProcedureFromCache

    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);
    }
开发者ID:jimmy00784,项目名称:mysql-connector-net,代码行数:32,代码来源:PerfMonTests.cs


示例9: CreateCounter

        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);
        }
开发者ID:HondaBey,项目名称:EnterpriseLibrary6,代码行数:25,代码来源:EnterpriseLibraryPerformanceCounterFactory.cs


示例10: BothCounters

		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);

					}
				}
			}
		}
开发者ID:zanyants,项目名称:mvp.xml,代码行数:31,代码来源:PerfCounterTests.cs


示例11: CollectMetric

        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;
        }
开发者ID:marqui678,项目名称:finalchance.Panopta,代码行数:34,代码来源:ServicePlugin.cs


示例12: Run

        /// <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);
                }
            }
        }
开发者ID:pxc,项目名称:BlinkStickDotNet,代码行数:33,代码来源:MemoryMonitor.cs


示例13: GetProcessAndParent

 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 };
 }
开发者ID:bluerv,项目名称:ApprovalTests.Net,代码行数:7,代码来源:VisualStudioReporter.cs


示例14: InstancePerformanceCounter

 public InstancePerformanceCounter(string name, string categoryName, string instanceName)
 {
     _performanceCounter = new PerformanceCounter(categoryName, name, instanceName, false)
         {
             RawValue = 0
         };
 }
开发者ID:jimitndiaye,项目名称:MassTransit,代码行数:7,代码来源:InstancePerformanceCounter.cs


示例15: Render

        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();
            }
        }
开发者ID:sparta25,项目名称:3DEngineResearch,代码行数:34,代码来源:TestHelper.cs


示例16: GPGPUProperties

        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;
            }
        }
开发者ID:JustasB,项目名称:cudafy,代码行数:33,代码来源:GPGPUProperties.cs


示例17: MainForm

        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();
        }
开发者ID:dalinhuang,项目名称:appcollection,代码行数:30,代码来源:MainForm.cs


示例18: TryToInitializeCounters

        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;
                }
            }
        }
开发者ID:hendrikdelarey,项目名称:appcampus,代码行数:26,代码来源:NetworkTrafficUtilities.cs


示例19: TryToInstantiatePerformanceCounter

        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;
        }
开发者ID:xqfgbc,项目名称:NServiceBus,代码行数:28,代码来源:PerformanceCounterHelper.cs


示例20: MachineStatus

        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
            };
        }
开发者ID:beomyeol,项目名称:reef,代码行数:26,代码来源:MachineStatus.cs



注:本文中的System.Diagnostics.PerformanceCounter类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Diagnostics.PerformanceCounterCategory类代码示例发布时间:2022-05-26
下一篇:
C# Diagnostics.LogSwitch类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap