2011-07-21 111 views
3

有沒有一種方法(C#中的類)可以讓我計算在程序中執行某些行所需的時間。計算一行或多行代碼的執行時間

例:

try 
{ 
    string connectionString = GetConnectionString(); 
    using (SqlConnection conn = new SqlConnection(connectionString)) 
    { 
    conn.Open(); 

    ***// start counting: 
    // time = 0*** 

    using (SqlCommand cmd = new SqlCommand(
    「SELECT * FROM Books」, conn)) 
     using (SqlDataReader reader = cmd.ExecuteReader()) 
     { 
     while (reader.Read()) 
      { 
      Console.WriteLine(「{0}\t{1}\t{2}」, 
      reader.GetInt32(0), 
      reader.GetString(1), 
      reader.GetInt32(2)); 
      } 

    ***// end counting 
    // time = 10 sec*** 
    } 
} 

回答

8

一種選擇是使用內置的Stopwatch類:

var sw = Stopwatch.StartNew(); 

// do something 

sw.Stop(); 
Console.WriteLine("Time elapsed: {0} milliseconds", sw.ElapsedMilliseconds); 
+1

它應該是秒錶「小後衛」,謝謝! – Shadi

1
static TimeSpan Time(Action action) { 
    var sw = StopWatch.StartNew(); 
    action(); 
    sw.Stop(); 
    return sw.Elapsed 
} 

然後,你可以做

VAR的時間=(()=> {//這裏mycode的});

+0

這會工作,但它會有大約15-16毫秒的精度,因爲DateTime.Now會跳過大約ms的值。 –