Pau*_*ews 13 c# performancecounter
启动和运行性能计数器的最小C#代码量是多少?
我只想测量代码中两点之间的CPU周期数和/或时间.我已经浏览了网络上的所有华夫饼干,但它似乎比这样一个微不足道的任务所需的代码更多.我只想快速测量并运行,并将更多精力放在我正在进行的工作上.
dri*_*iis 30
我不认为你需要一个性能计数器.你需要的时间超过了从StopWatch获得的时间吗?这非常准确.
Stopwatch watch = Stopwatch.StartNew();
// Do work
watch.Stop();
// elapsed time is in watch.Elapsed
Run Code Online (Sandbox Code Playgroud)
但是,要回答您实际问过的问题:如果您只想查询现有计数器,实际上非常简单.这是一个完整的例子:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当然,该过程需要适当的权限才能访问您需要的性能计数器.
我喜欢可以接受任何代码块的东西,并用秒表分析代码包装它来测量执行它所花费的时间:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后这样称呼它:
Profile(() => MyObj.MySlowMethod());
Run Code Online (Sandbox Code Playgroud)
要么:
Profile(() => MyObj.MySlowMethod(), "I can explain why");
Run Code Online (Sandbox Code Playgroud)