我想测量托管(.NET)线程的性能。具体来说,我需要测量以下内容 -如何在.NET中测量托管线程的性能
线程使用CPU多长时间?
它被阻塞多久(等待远程方法调用的完成)?
使用System.Diagnostic.StopWatch是没有帮助的,原因是其读取OS /硬件可能包括通过平行运行,并共享相同的CPU其它线程所消耗时间的高分辨率性能的定时器功能。
我想测量托管(.NET)线程的性能。具体来说,我需要测量以下内容 -如何在.NET中测量托管线程的性能
线程使用CPU多长时间?
它被阻塞多久(等待远程方法调用的完成)?
使用System.Diagnostic.StopWatch是没有帮助的,原因是其读取OS /硬件可能包括通过平行运行,并共享相同的CPU其它线程所消耗时间的高分辨率性能的定时器功能。
您可以使用方法说明这里http://www.codeproject.com/KB/dotnet/ExecutionStopwatch.aspx 它使用系统功能GetThreadTimes http://msdn.microsoft.com/en-us/library/ms683237(v=vs.85).aspx
等待时间为总时间和执行时间之间的差。
补充: 我喜欢用一次性类来衡量性能 - 它使代码更干净(硬编码控制台的使用只是举例):
public class ThreadPerformance : IDisposable
{
private Stopwatch _totalStopwatch = new Stopwatch();
private ExecutionStopwatch _executionStopwatch = new ExecutionStopwatch();
public static ThreadPerformance Measure()
{
return new ThreadPerformance();
}
private ThreadPerformance()
{
_totalStopwatch.Start();
_executionStopwatch.Start();
}
public void Dispose()
{
_executionStopwatch.Stop();
_totalStopwatch.Stop();
Console.WriteLine("Performance mesurement for thread {0}", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Waiting: {0}", _totalStopwatch.Elapsed - _executionStopwatch.Elapsed);
Console.WriteLine("CPU usage: {0}", _executionStopwatch.Elapsed);
}
}
用法很简单:
static void ThreadProc()
{
using (ThreadPerformance.Measure())
{
// do some calculations and waitings here
}
}
谢谢lazyberezovsky。我在同一线路上思考。我不确定此解决方案在不同操作系统平台/ .NET版本/硬件平台上是否可以正常工作。 Microsoft文档不保证.NET托管线程将始终映射到同一个非托管线程。如果GetCurrentThread()在两个单独的调用中返回不同的线程句柄会怎么样? – Nitin 2011-01-20 16:58:47