计算一行或多行代码的执行时间

时间:2011-07-21 13:14:59

标签: c# c#-4.0

是否有办法(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***
  }
} 

4 个答案:

答案 0 :(得分:8)

一种选择是使用内置的Stopwatch类:

var sw = Stopwatch.StartNew();

// do something

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

答案 1 :(得分:2)

请参阅System.Diagnostics.StopWatch课程以手动执行或考虑使用profiler

答案 2 :(得分:1)

答案 3 :(得分:1)

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

然后你可以做

var time = Time(()=> {// MyCode here});