本文整理汇总了C#中System.Diagnostics.PerformanceCounter类的典型用法代码示例。如果您正苦于以下问题:C# PerformanceCounter类的具体用法?C# PerformanceCounter怎么用?C# PerformanceCounter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
PerformanceCounter类属于System.Diagnostics命名空间,在下文中一共展示了PerformanceCounter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RAM_Count
public int RAM_Count()
{
PerformanceCounter perfMemCount = new PerformanceCounter("Memory", "Available MBytes");
perfMemCount.NextValue();
short currentAvailableMemory = (short)perfMemCount.NextValue();
return currentAvailableMemory;
}
示例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();
}
示例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;
}
示例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);
}
}
示例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");
}
示例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);
}
示例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)
{
}
}
}
示例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);
}
示例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);
}
示例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);
}
}
}
}
示例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;
}
示例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);
}
}
}
示例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 };
}
示例14: InstancePerformanceCounter
public InstancePerformanceCounter(string name, string categoryName, string instanceName)
{
_performanceCounter = new PerformanceCounter(categoryName, name, instanceName, false)
{
RawValue = 0
};
}
示例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();
}
}