I want to measure performance of a managed (.NET) thread. To be specific, I need to measure following -
How long the thread is using CPU?
How long it remained blocked (waiting for completion of a remote method call)?
Using System.Diagnostic.StopWatch is not helpful, becuase it reads high resolution performance timers feature of OS/Hardware which may include time consumed by other threads running parallely and sharing the same CPU.
You can use approach described here http://www.codeproject.com/KB/dotnet/ExecutionStopwatch.aspx which uses system function GetThreadTimes http://msdn.microsoft.com/en-us/library/ms683237(v=vs.85).aspx
Waiting time is the difference between total time and execution time.
Added: I like to use disposable class to measure performance - it keeps code clean (hardcoded console usage just for example):
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);
}
}
Usage is very simple:
static void ThreadProc()
{
using (ThreadPerformance.Measure())
{
// do some calculations and waitings here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With