Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure performance of a managed thread in .NET

I want to measure performance of a managed (.NET) thread. To be specific, I need to measure following -

  1. How long the thread is using CPU?

  2. 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.

like image 741
Nitin Avatar asked Jan 20 '11 10:01

Nitin


1 Answers

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
    }
}
like image 193
Sergey Berezovskiy Avatar answered Sep 19 '22 07:09

Sergey Berezovskiy