开发者

Calculate execution time of one or more lines of code

Is there a way (a class-made in C #) that would allow me to calculate the time required to execute some lines in my program.

Ex :

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())
     开发者_Python百科     {
             Console.WriteLine(“{0}\t{1}\t{2}”, 
             reader.GetInt32(0),
             reader.GetString(1), 
             reader.GetInt32(2));
          }

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


One option is to use the built-in Stopwatch class:

var sw = Stopwatch.StartNew();

// do something

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


See the System.Diagnostics.StopWatch class to do it manually or consider using a profiler.


Look at System.Diagnostics.Stopwatch


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

Then you can just do

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜