启动和运行性能计数器的最小C#代码量是多少?
我只想测量代码中两点之间的CPU周期数和/或时间。我已经浏览了网络上的所有华夫饼干,但它似乎比这样一个微不足道的任务所需的代码更多。我只是希望快速测量并运行,并将更多精力放在我正在进行的工作上。
答案 0 :(得分:30)
我认为你不需要性能计数器。您需要的时间超过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);
}
}
}
当然,该过程需要适当的权限才能访问您需要的性能计数器。
答案 1 :(得分:9)
我喜欢可以接受任何代码块的东西,并用秒表分析代码包装它来测量执行它所花费的时间:
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");
答案 2 :(得分:2)
没有琐碎的方法可以在.NET中启动并运行它。但是,我发现最简单的方法是在Enterprise Library之上构建,它提供了一些用于处理性能计数器的开箱即用功能。例如:the Performance Counter Handler
企业库还为您提供了一些功能,可以更轻松地管理性能计数器的安装。
此外,它让你建立在它之上,所以,你可以创建一个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
}
}
这允许您简单地将要监视的代码封装在using块中 - 并专注于您实际想要处理的代码,而不是担心所有性能计数器基础结构。
为此,您将创建一个可重复使用的AverageTimeMeter类,如下所示:
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示例中),但这应该是您的开始。