如何编写最简单的C#代码来启动性能计数器?
我只想测量我的代码中两个时间点之间的CPU周期数和/或时间。我已经浏览了很多相关网页,但似乎对于这样一个微不足道的任务,需要的代码远比实际需要的要多得多。我只是想快速地启动一个测量,并更加专注于我的工作。
如何编写最简单的C#代码来启动性能计数器?
我只想测量我的代码中两个时间点之间的CPU周期数和/或时间。我已经浏览了很多相关网页,但似乎对于这样一个微不足道的任务,需要的代码远比实际需要的要多得多。我只是想快速地启动一个测量,并更加专注于我的工作。
我认为你不需要性能计数器。你是否需要比从StopWatch获取的时间更多的信息?它非常准确。
Stopwatch watch = Stopwatch.StartNew();
// Do work
watch.Stop();
// elapsed time is in watch.Elapsed
然而,回答你实际提出的问题:如果你只想查询现有的计数器,那么这实际上非常简单。以下是完整示例:
using System;
using System.Diagnostics;
using System.Linq;
static class Test
{
static void Main()
{
var processorCategory = PerformanceCounterCategory.GetCategories()
.FirstOrDefault(cat => cat.CategoryName == "Processor");
var countersInCategory = processorCategory.GetCounters("_Total");
DisplayCounter(countersInCategory.First(cnt => cnt.CounterName == "% Processor Time"));
}
private static void DisplayCounter(PerformanceCounter performanceCounter)
{
while (!Console.KeyAvailable)
{
Console.WriteLine("{0}\t{1} = {2}",
performanceCounter.CategoryName, performanceCounter.CounterName, performanceCounter.NextValue());
System.Threading.Thread.Sleep(1000);
}
}
}
我喜欢能够将任何代码块包装在秒表分析代码中,以测量执行它所花费的时间:
using System.Diagnostics;
using System.Threading;
public static T Profile<T>(Func<T> codeBlock, string description = "")
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
T res = codeBlock();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
const double thresholdSec = 2;
double elapsed = ts.TotalSeconds;
if(elapsed > thresholdSec)
System.Diagnostics.Debug.Write(description + " code was too slow! It took " +
elapsed + " second(s).");
return res;
}
然后像这样调用它:
Profile(() => MyObj.MySlowMethod());
或者:
Profile(() => MyObj.MySlowMethod(), "I can explain why");
在.NET中,没有简单的方法来启动和运行此功能。然而,我发现最简单的方法是在企业库的基础上构建,该库提供了一些开箱即用的功能来处理性能计数器。例如:性能计数器处理程序
企业库还提供了一些功能,更容易地管理性能计数器的安装。
此外,它让您在其基础上构建,因此您可以创建一个AvergeTimeMeter,使您只需执行以下操作:
private static EnterpriseLibraryPerformanceCounter averageRequestTimeCounter = PerformanceCounterManager.GetEnterpriseLibraryCounter(MadPerformanceCountersListener.AverageRequestTime);
private static EnterpriseLibraryPerformanceCounter averageRequestTimeCounterBase = PerformanceCounterManager.GetEnterpriseLibraryCounter(MadPerformanceCountersListener.AverageRequestTimeBase);
public void DoSomethingWeWantToMonitor()
{
using (new AverageTimeMeter(averageRequestTimeCounter, averageRequestTimeCounterBase))
{
// code here that you want to perf mon
}
}
public sealed class AverageTimeMeter : IDisposable
{
private EnterpriseLibraryPerformanceCounter averageCounter;
private EnterpriseLibraryPerformanceCounter baseCounter;
private Stopwatch stopWatch;
private string instanceName;
public AverageTimeMeter(EnterpriseLibraryPerformanceCounter averageCounter, EnterpriseLibraryPerformanceCounter baseCounter, string instanceName = null)
{
this.stopWatch = new Stopwatch();
this.averageCounter = averageCounter;
this.baseCounter = baseCounter;
this.instanceName = instanceName;
this.stopWatch.Start();
}
public void Dispose()
{
this.stopWatch.Stop();
if (this.baseCounter != null)
{
this.baseCounter.Increment();
}
if (this.averageCounter != null)
{
if (string.IsNullOrEmpty(this.instanceName))
{
this.averageCounter.IncrementBy(this.stopWatch.ElapsedTicks);
}
else
{
this.averageCounter.SetValueFor(this.instanceName, this.averageCounter.Value + this.stopWatch.ElapsedTicks);
}
}
}
}
您需要注册性能计数器(在EntLib示例中显示),但这应该可以让您开始。