当前位置: 首页>>代码示例>>C#>>正文


C# PerformanceCounter.NextSample方法代码示例

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


在下文中一共展示了PerformanceCounter.NextSample方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: WatchCpuAndMemory

        public void WatchCpuAndMemory()
        {
            var pc = new PerformanceCounter("Processor Information", "% Processor Time");
            var cat = new PerformanceCounterCategory("Processor Information");
            var cpuInstances = cat.GetInstanceNames();
            var cpus = new Dictionary<string, CounterSample>();

            var memoryCounter = new PerformanceCounter("Memory", "Available MBytes");

            foreach (var s in cpuInstances)
            {
                pc.InstanceName = s;
                cpus.Add(s, pc.NextSample());
            }
            var t = DateTime.Now;
            while (t.AddMinutes(1) > DateTime.Now)
            {
                Trace.WriteLine(string.Format("Memory:{0}MB", memoryCounter.NextValue()));

                foreach (var s in cpuInstances)
                {
                    pc.InstanceName = s;
                    Trace.WriteLine(string.Format("CPU:{0} - {1:f}", s, Calculate(cpus[s], pc.NextSample())));
                    cpus[s] = pc.NextSample();
                }

                //Trace.Flush();
                System.Threading.Thread.Sleep(1000);
            }
        }
开发者ID:LeeWangyeol,项目名称:Scut,代码行数:30,代码来源:UtilsTest.cs

示例2: FirePerfCounter

        protected void FirePerfCounter(string category, string counterName, PerfCounterEventDelegate action)
        {
            PerformanceCounter counter = new PerformanceCounter(category, counterName, "_total_");
            CounterSample sample = counter.NextSample();
            float startVal = sample.RawValue;

            action();
            action();
            action();

            sample = counter.NextSample();
            float endVal = sample.RawValue;

            Assert.AreEqual(startVal + 3, endVal);
        }
开发者ID:bnantz,项目名称:NCS-V1-1,代码行数:15,代码来源:PerformanceCounterFixtureBase.cs

示例3: CpuUtilization

        public ActionResult CpuUtilization()
        {
            PerformanceCounter cpuCounter = new PerformanceCounter
            {
                CategoryName = "Processor",
                CounterName = "% Processor Time",
                InstanceName = "_Total"
            };

            var sample1 = cpuCounter.NextSample();
            System.Threading.Thread.Sleep(100);
            var sample2 = cpuCounter.NextSample();
            var finalCpuCounter = CounterSample.Calculate(sample1, sample2);

            return Json(Math.Round(finalCpuCounter,2).ToString() + "%", JsonRequestBehavior.AllowGet);
        }
开发者ID:kevintan1983,项目名称:points,代码行数:16,代码来源:AjaxController.cs

示例4: GetElapsedTimeSampler

		static Func<ulong> GetElapsedTimeSampler(PerformanceCounter pc) {
			var scale = 1.0 / 1000;
			return () => {
				var sample = pc.NextSample();
				return (ulong)((sample.CounterTimeStamp - sample.RawValue) / (scale * sample.CounterFrequency));
			};
		}
开发者ID:drunkcod,项目名称:StatsSharp,代码行数:7,代码来源:StatsAgent.cs

示例5: WaitForNextRawValue

 private static long WaitForNextRawValue(PerformanceCounter counter)
 {
     long used;
     while((used = counter.NextSample().RawValue) == 0)
     {
         Thread.Sleep(10);
     }
     return used;
 }
开发者ID:anton-gogolev,项目名称:metrics-net,代码行数:9,代码来源:CLRProfiler.cs

示例6: NetworkAdapter

    private string _name; // The name of the adapter.

    #endregion

    #region Private methods

    /// <summary>
    /// Instances of this class are supposed to be created only in an NetworkMonitorHandler.
    /// </summary>
    internal NetworkAdapter(string name)
    {
      _name = name;

      // Create performance counters for the adapter.
      _dlCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", this._name);
      _ulCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", this._name);

      // Since dlValueOld and ulValueOld are used in method update() to calculate network speed,
      // they must have be initialized.
      _dlValueOld = _dlCounter.NextSample().RawValue;
      _ulValueOld = _ulCounter.NextSample().RawValue;
    }
开发者ID:arangas,项目名称:MediaPortal-1,代码行数:22,代码来源:ActiveNetworkStandbyHandler.cs

示例7: GetCpusUsage

        public Dictionary<string, float> GetCpusUsage()
        {
            performanceCounter = new PerformanceCounter("Processor Information", "% Processor Time");
            var counterCategory = new PerformanceCounterCategory("Processor Information");
            var instances = counterCategory.GetInstanceNames();
            var samples = instances.ToDictionary(x=>x,y=>new List<CounterSample>());

            for (int i = 0; i < 2; i++)
            {
                foreach (var instanceName in instances)
                {
                    performanceCounter.InstanceName = instanceName;
                    samples[instanceName].Add(performanceCounter.NextSample());
                    Thread.Sleep(100);
                }
            }
            return samples.ToDictionary(x => x.Key, y => Calculate(y.Value[0], y.Value[1]));
        }
开发者ID:wjch-krl,项目名称:Affrodite,代码行数:18,代码来源:PerformanceManager.cs

示例8: DiskActivity

        public DiskActivity(int interval = 1000)
        {
            _performanceCounter = new PerformanceCounter("PhysicalDisk", "% Idle Time");
            var performanceCounterCategory = new PerformanceCounterCategory("PhysicalDisk");
            _instances = performanceCounterCategory.GetInstanceNames();
            _counterSamples = new Dictionary<string, CounterSample>();

            foreach (var s in _instances)
            {
                _performanceCounter.InstanceName = s;
                _counterSamples.Add(s, _performanceCounter.NextSample());
            }

            _updateTimer = new Timer
            {
                AutoReset = true,
                Interval = interval
            };

            _updateTimer.Elapsed += UpdateTimerOnElapsed;

            _updateTimer.Start();
        }
开发者ID:MadSprayerDK,项目名称:ComputerControl,代码行数:23,代码来源:DiskActivity.cs

示例9: CpuLoad

        public CpuLoad(int interval = 1000)
        {
            _performanceCounter = new PerformanceCounter("Processor Information", "% Processor Time");
            var performanceCounterCategory = new PerformanceCounterCategory("Processor Information");
            _instances = performanceCounterCategory.GetInstanceNames();
            _counterSamples = new Dictionary<string, CounterSample>();

            foreach (var s in _instances)
            {
                _performanceCounter.InstanceName = s;
                _counterSamples.Add(s, _performanceCounter.NextSample());
            }

            _updateTimer = new Timer
            {
                AutoReset = true,
                Interval = interval
            };

            _updateTimer.Elapsed += UpdateTimerOnElapsed;

            _updateTimer.Start();
        }
开发者ID:MadSprayerDK,项目名称:ComputerControl,代码行数:23,代码来源:CpuLoad.cs

示例10: SafelyGetPerformanceCounter

		public static long? SafelyGetPerformanceCounter(string categoryName, string counterName, string processName)
		{
			try
			{
				if (PerformanceCounterCategory.Exists(categoryName) == false)
					return null;
				var category = new PerformanceCounterCategory(categoryName);
				var instances = category.GetInstanceNames();
				var ravenInstance = instances.FirstOrDefault(x => x == processName);
				if (ravenInstance == null || !category.CounterExists(counterName))
				{
					return null;
				}
				using (var counter = new PerformanceCounter(categoryName, counterName, ravenInstance, readOnly: true))
				{
					return counter.NextSample().RawValue;
				}
			}
			catch (Exception e)
			{
				//Don't log anything here, it's up to the calling code to decide what to do
				return null;
			}
		}
开发者ID:nberardi,项目名称:ravendb,代码行数:24,代码来源:PerformanceCountersUtils.cs

示例11: Main

        static void Main(string[] args)
        {
            // Getting Hostname.
            var Hostname = System.Environment.MachineName;

            // Making sure that the command is being run with Argument Values.
            if (args.Length == 0)
            {
                Console.WriteLine("A [Processor_Instance], [Warning Percent] and a [Critical Percent] Value must be provided!");
                Environment.Exit(3);
            }

            try
            {

                // Declared Argument Values for Disk, Warning Threshold and Critical Threshold.
                String Arg_0 = args[0];
                String Arg_1 = args[1];
                String Arg_2 = args[2];

                // Testing Argument Variables to determine if they are the correct type of value.
                Match ProcessorInstanceCheck = Regex.Match(Arg_0, @"[A-Z]", RegexOptions.IgnoreCase);
                Match WarningCheck           = Regex.Match(Arg_1, @"[A-Z]", RegexOptions.IgnoreCase);
                Match CriticalCheck          = Regex.Match(Arg_2, @"[A-Z]", RegexOptions.IgnoreCase);

                // Making sure that the Warning Percent Decimal Value is a number.
                if (ProcessorInstanceCheck.Success)
                {
                    Console.WriteLine("A [Proceesor_Instance] Numeric Value (0,1,2,5 etc...) must be provided!");
                    Environment.Exit(3);
                }

                // Making sure that the Warning Percent Decimal Value is a number.
                if (WarningCheck.Success)
                {
                    Console.WriteLine("A [Warning Percent] Decimal Value (1.00, 12.00, 90.00 etc...) must be provided!");
                    Environment.Exit(3);
                }

                // Making sure that the Critical Percent Decimal Value is a number.
                if (CriticalCheck.Success)
                {
                    Console.WriteLine("A [Critical Percent] Decimal Value (1.00, 12.00, 90.00 etc...) must be provided!");
                    Environment.Exit(3);
                }

                // Converting all Passed Arguments into a Usable State.
                var Warning      = (Convert.ToDouble(args[1]));
                var Critical     = (Convert.ToDouble(args[2]));

                // Making sure that the Warning Percent and Critical Percent Values are not greater than 100%
                if ((Warning > 100.00) || (Critical > 100.00))
                {
                    Console.WriteLine("The [Warning Percent] and [Critical Percent] Values cannot be greater than 100.00!");
                    Environment.Exit(3);
                }

                // Making sure that the Warning Percent Value is Less than the Critical Percent Value.
                if (Warning > Critical)
                {
                    Console.WriteLine("The [Warning Percent] Value must be Less than the [Critical Percent] Value!");
                    Environment.Exit(3);
                }

                // Making sure that the Warning Percent Value is not equal to the Critical Percent Value.
                else if (Warning == Critical)
                {
                    Console.WriteLine("The [Warning Percent] Value cannot be Equal to the [Critical Percent] Value!");
                    Environment.Exit(3);
                }

                // Checking to see if the Processor Instance exists.
                if (!System.Diagnostics.PerformanceCounterCategory.InstanceExists(args[0], "Processor"))
                {
                    Console.WriteLine("Processor Instance [{0}] does not exist on {1}!", args[0], Hostname);
                    Environment.Exit(3);
                }

                // Processor Instance is queried.
                var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", args[0], true);

                // Calculating the % Processor Time of the chosen Processor Instance.
                var Sample_1 = cpuCounter.NextSample(); System.Threading.Thread.Sleep(1000);
                var Sample_2 = cpuCounter.NextSample();

                var ProcessorTime = ((1 - ((double)(Sample_2.RawValue - Sample_1.RawValue) / (double)(Sample_2.TimeStamp100nSec - Sample_1.TimeStamp100nSec))) * 100);

                // Final Results and Performance Data are Returned.
                if (ProcessorTime > Critical)
                {
                    Console.WriteLine("[{0}]: % Processor Time = {1}% - CRITICAL | '[{0}]'={1}%;{2};{3};0.00;100.00;", args[0], ProcessorTime.ToString("0.00"), Warning.ToString("0.00"), Critical.ToString("0.00"));
                    Environment.Exit(2);
                }

                else if ((ProcessorTime < Critical) && (ProcessorTime > Warning))
                {
                    Console.WriteLine("[{0}]: % Processor Time = {1}% - WARNING | '[{0}]'={1}%;{2};{3};0.00;100.00;", args[0], ProcessorTime.ToString("0.00"), Warning.ToString("0.00"), Critical.ToString("0.00"));
                    Environment.Exit(1);
                }

//.........这里部分代码省略.........
开发者ID:starkfell,项目名称:Howler-WinPlugins,代码行数:101,代码来源:single_cpu_usage_check.cs

示例12: GetPerformanceCounterSample

 public static CounterSample GetPerformanceCounterSample(string categoryName,
                                                         string instanceName,
                                                         string counterName)
 {
     using (PerformanceCounter counter = new PerformanceCounter())
     {
         counter.CategoryName = categoryName;
         counter.CounterName = counterName;
         counter.InstanceName = instanceName;
         return counter.NextSample();
     }
 }
开发者ID:HondaBey,项目名称:EnterpriseLibrary6,代码行数:12,代码来源:CommonUtil.cs

示例13: LogPerformanceCounterData

 private void LogPerformanceCounterData(PerformanceCounter memoryMonitor, PerformanceCounter processorMonitor)
 {
     LogMessage(string.Format("\t\tMemory Usage:\t{0,15:N0}", memoryMonitor.NextSample().RawValue));
     LogMessage(string.Format("\t\tProcessor Usage:{0,15:N0}", processorMonitor.NextSample().RawValue));
 }
开发者ID:stanroze,项目名称:orleans,代码行数:5,代码来源:ChirperNetworkGenerator.cs

示例14: MonitorInventory


//.........这里部分代码省略.........
            ReaderRequest readerRequest = new ReaderRequest( );
            readerRequest.reader = _theReaderID.Name;
#pragma warning disable 420 // reference to a volatile field is valid for Interlocked call
            readerRequest.requestSequence = System.Threading.Interlocked.Increment( ref _commonRequestIndex );
#pragma warning restore 420
            readerRequest.requestName = rfidReader.GetNameForRequest( rfidReader.ReaderRequestType.TagAccess );
            readerRequest.startTime = GetSessionRelativeDateTime( report.StartTimeMS );
            readerRequest.requestStartTime = report.StartTimeMS;
            readerRequest.startingPacketCount = RawPacketCount;
            readerRequest.startingTagCount = RawInventoryCount;

            MemoryStream data = new MemoryStream( );
            readerRequest.WriteTo( data );
            PacketData.PacketWrapper pseudoPacket = new PacketData.PacketWrapper( new PacketData.CommandPsuedoPacket( readerRequest.requestName, data.ToArray( ) ), PacketData.PacketType.U_N_D_F_I_N_E_D );
            pseudoPacket.IsPseudoPacket = true;
            pseudoPacket.ReaderName = _theReaderID.Name;
            pseudoPacket.ReaderIndex = ( int ) _theReaderID.Handle;
            FileHandler.WritePacket( pseudoPacket );

            //clark 2011.2.18 Record that user request data length
            TagAccessReqCount = r_iTagAccessReqCount;
            TagAccessReqCountRead = r_iTagAccessReqCountRead;//把计??

            DateTime ReportDue = DateTime.Now.AddMilliseconds( refreshMS );
            threadClass.StartEvent.Set( );

            while ( runnerThread.IsAlive )
            {
                CounterSample sample = CounterSample.Empty;
                if ( processorUtilizationCounter != null )
                {
                    try
                    {
                        sample = processorUtilizationCounter.NextSample( );
                    }
                    catch ( Exception ) { }
                }
                ProcessQueuedPackets( );

                QueueEvent.WaitOne( 30, true );
                QueueEvent.Reset( );

                DateTime now = DateTime.Now;

                if ( ReportDue.Ticks <= now.Ticks )
                {
                    //Debug.WriteLine(String.Format("Reporing Progress Now (Elapsed Milliseconds {0})", ElapsedMilliseconds));
                    _bgdWorker.ReportProgress(
                        0,
                        report.GetProgressReport( ElapsedMilliseconds,
                                                  RequestCount,
                                                  RawAntennaCycleCount,
                                                  RawInventoryCycleCount,
                                                  BadPacketCount,
                                                  CRCErrorCount,
                                                  RawPacketCount,
                                                  RawRoundCount,
                                                  RawInventoryCount,
                                                  SessionUniqueTags,
                                                  RequestUniqueTags,
                                                  CurrentUniqueTags,
                                                  SessionDuration ) );
                    _periodTagList.Clear( );
                    ReportDue = now.AddMilliseconds( refreshMS );
                }
开发者ID:mti-rfid,项目名称:RFID_Explorer,代码行数:66,代码来源:LakeChabot.cs

示例15: DoLoop

        private void DoLoop()
        {
            _conn = new UdpClient(_options.PhoneIp, _options.PhonePort);

            var ramFreeCounter = new PerformanceCounter("Memory", "Available MBytes");
            var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            var totalRam = computerInfo.TotalPhysicalMemory / 1024 / 1024;

            CreateNetworkCounters();

            var pc = new PerformanceCounter("Processor", "% Processor Time");
            var instances = new PerformanceCounterCategory("Processor").GetInstanceNames();
            var cs = new Dictionary<string, CounterSample>();

            foreach (var s in instances)
            {
                pc.InstanceName = s;
                cs.Add(s, pc.NextSample());
            }
            Thread.Sleep(999);

            var drives = DriveInfo.GetDrives();

            var volume = new Volume();

            _getIpsBw.DoWork += GetIps;
            //_getIpsBw.RunWorkerAsync(true);

            var myipTimer = new Timer(StartBw, null, TimeSpan.Zero, TimeSpan.FromMinutes(_options.MyipInterval));

            while (_continue)
            {
                var startTime = DateTime.Now;

                var strout = ".start.";
                foreach (var s in instances)
                {
                    pc.InstanceName = s;
                    var ns = pc.NextSample();
                    if (s.Equals("_Total")) strout += s + "|" + Math.Round(CounterSample.Calculate(cs[s], ns), 2) + "\n";
                    else strout += s + "|" + Math.Round(CounterSample.Calculate(cs[s], ns), 0) + "\n";
                    cs[s] = ns;
                }
                strout += "MemUsed|" + (totalRam - ramFreeCounter.NextValue()) + "\n";
                strout += "MemTotal|" + totalRam + "\n";

                try
                {
                    strout += "NetIn|" + networkInCounter.NextValue() + "\n";
                    strout += "NetOut|" + networkOutCounter.NextValue() + "\n";
                }
                catch (Exception e)
                {
                    _mainForm.LogLine("Warning: Failed to get network activity: " + e);
                    _mainForm.LogLine("Resetting to first adapter.");
                    _options.NetIndex = 0;
                    CreateNetworkCounters();
                }
                strout += "LocalIp|" + _localIp + "\n";
                strout += "RemoteIp|" + _remoteIp + "\n";

                if (RescanDrives)
                {
                    _mainForm.LogLine("Drivechange detected, rescanning drives.", true);
                    drives = DriveInfo.GetDrives();
                    RescanDrives = false;
                }
                foreach (var drive in drives.Where(drive => drive.DriveType == DriveType.Fixed))
                {
                    try
                    {
                        strout += "DriveInfo|" + drive.Name + "|" + drive.AvailableFreeSpace + "\n";
                    }
                    catch
                    {

                    }
                }

                strout += "Np|" + GetNp() + "\n";

                var muteStatus = volume.GetMute();
                var vol = volume.GetVol();

                strout += "mute|" + (muteStatus ? "1" : "0") + "\n";
                strout += "vol|" + vol + "\n";

                SendInfo(strout);

                var duration = DateTime.Now - startTime;
                if (duration.Milliseconds > 1000)
                {
                    _mainForm.LogLine("Warning: Iterating took " + duration.Milliseconds + "ms, should be less than 1s.");
                }
                else _mainForm.LogLine("Iterating took " + duration.Milliseconds + "ms", true);
                Thread.Sleep(1000 - duration.Milliseconds);
            }

            ramFreeCounter.Close();
            pc.Close();
//.........这里部分代码省略.........
开发者ID:Logima,项目名称:vinfo-server,代码行数:101,代码来源:LoopThread.cs


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