2011-01-20 53 views
10

我想測量託管(.NET)線程的性能。具體來說,我需要測量以下內容 -如何在.NET中測量託管線程的性能

  1. 線程使用CPU多長時間?

  2. 它被阻塞多久(等待遠程方法調用的完成)?

使用System.Diagnostic.StopWatch是沒有幫助的,原因是其讀取OS /硬件可能包括通過平行運行,並共享相同的CPU其它線程所消耗時間的高分辨率性能的定時器功能。

回答

4

您可以使用方法說明這裏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 
    } 
} 
+1

謝謝lazyberezovsky。我在同一線路上思考。我不確定此解決方案在不同操作系統平臺/ .NET版本/硬件平臺上是否可以正常工作。 Microsoft文檔不保證.NET託管線程將始終映射到同一個非託管線程。如果GetCurrentThread()在兩個單獨的調用中返回不同的線程句柄會怎麼樣? – Nitin 2011-01-20 16:58:47