2011-07-21 22 views
3

私のプログラムでいくつかの行を実行するのに必要な時間を計算する方法がありますか?1行以上のコードの実行時間を計算する

例:

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

ストップウオッチ「wの後半」になります。ありがとうございます! – Shadi

1

ルックを行うことができます。

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

+0

これは動作しますが、DateTime.Nowは約msの値をジャンプするので、15-16ミリ秒程度の精度があります。 –

関連する問題