2013-04-21 27 views
9

私の大学の画像ステガノグラフィープロジェクトを作成しています。私はプロジェクトを終了し、画像にデータを隠すためのいくつかの異なるアルゴリズムを保持しています。メソッドの実行時間を確認

私が尋ねたいのは、プログラム内の2つのポイント間で実行/実行時間を見つけることができる方法がC#に​​あることです。 は例

//Some Code 
//Code to start recording the time. 
hideDataUsingAlgorithm(); 
//Code to stop recording and get the time of execution of the above function. 

のために私は(同じデータと同じ画像を使用して)簡単な(あまり時間がかかる)と、より効率的なが、時間のかかるアルゴリズムの違いを示すために、これをやりたいです。私は約10の異なるアルゴリズムの色とGrayScaleイメージがあります。

マルチスレッド化されていないので、問題はありません。 Theresはただ1つの主なスレッドです。

+0

[コード実行時間の測定](https://stackoverflow.com/questions/16376191/measuring-code-execution-time)の重複の可能性があります - これは数日前ですが、[note](https: /meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled/)、 "*一般的な規則は、回答を最良の集まりで保持し、もう一方を複製として閉じることです。* " – ruffin

答えて

12
+3

パフォーマンステストのためには、必ず「Stopwatch」クラスを使用してください。 TickCountは、ベンチマークにはあまり役に立ちません。 –

4

あなたはStopWatchクラスを使用することができます。

var timer = System.Diagnostics.StopWatch.StartNew(); 
hideDataUsingAlgorithm(); 
timer.Stop(); 
var elapsed = timer.ElapsedMilliseconds; 
14

これは、ストップウォッチのための便利な拡張メソッドです:

public static class StopwatchExt 
{ 
    public static string GetTimeString(this Stopwatch stopwatch, int numberofDigits = 1) 
    { 
     double time = stopwatch.ElapsedTicks/(double)Stopwatch.Frequency; 
     if (time > 1) 
      return Math.Round(time, numberofDigits) + " s"; 
     if (time > 1e-3) 
      return Math.Round(1e3 * time, numberofDigits) + " ms"; 
     if (time > 1e-6) 
      return Math.Round(1e6 * time, numberofDigits) + " µs"; 
     if (time > 1e-9) 
      return Math.Round(1e9 * time, numberofDigits) + " ns"; 
     return stopwatch.ElapsedTicks + " ticks"; 
    } 
} 

はこのようにそれを使用します。

Stopwatch stopwatch = Stopwatch.StartNew(); 
//Call your method here 
stopwatch.Stop(); 
Console.WriteLine(stopwatch.GetTimeString()); 
0

あなたは、あなたのテストメソッドにデリゲートを宣言しに次の拡張メソッドのいずれかを使用することができますそれをN回実行する。すべての有用な値である

  • 最初の呼び出し時
  • 経過時間
  • コール頻度

:あなたがコンソールに出力を取得渡されたフォーマット文字列に基づいています。拡張メソッドは、最高精度を得るためにストップウォッチを使用します。

Action acc = hideDataUsingAlgorithm; 
acc.Profile(100*1000, "Method did run {runs} times in {time}s, Frequency: {frequency}"); 

は、問題のメソッドがタイミングを歪める空のメソッドがない場合は、あなたが簡単にあなたの方法を確認することができます

acc.ProfileFirst(100*1000, "First call {0}s", "Method did run {runs} times in {time}s, Frequency: {frequency}"); 

この方法を使用することができますまた、スタートアップの効果を確認するには、デリゲートの呼び出しがあろうからあなたのメソッド呼び出しに匹敵するものでなければなりません。元のアイデアはブログhereです。

詳細なコール時間分析の場合、プロファイラも非常に便利です。問題を診断するには、これらを使用するようにしてください。

using System; 
using System.Globalization; 
using System.Diagnostics; 

namespace PerformanceTester 
{ 
    /// <summary> 
    /// Helper class to print out performance related data like number of runs, elapsed time and frequency 
    /// </summary> 
    public static class Extension 
    { 
     static NumberFormatInfo myNumberFormat; 

     static NumberFormatInfo NumberFormat 
     { 
      get 
      { 
       if (myNumberFormat == null) 
       { 
        var local = new CultureInfo("en-us", false).NumberFormat; 
        local.NumberGroupSeparator = " "; // set space as thousand separator 
        myNumberFormat = local; // make a thread safe assignment with a fully initialized variable 
       } 
       return myNumberFormat; 
      } 
     } 

     /// <summary> 
     /// Execute the given function and print the elapsed time to the console. 
     /// </summary> 
     /// <param name="func">Function that returns the number of iterations.</param> 
     /// <param name="format">Format string which can contain {runs} or {0},{time} or {1} and {frequency} or {2}.</param> 
     public static void Profile(this Func<int> func, string format) 
     { 

      Stopwatch watch = Stopwatch.StartNew(); 
      int runs = func(); // Execute function and get number of iterations back 
      watch.Stop(); 

      string replacedFormat = format.Replace("{runs}", "{3}") 
             .Replace("{time}", "{4}") 
             .Replace("{frequency}", "{5}"); 

      // get elapsed time back 
      float sec = watch.ElapsedMilliseconds/1000.0f; 
      float frequency = runs/sec; // calculate frequency of the operation in question 

      try 
      { 
       Console.WriteLine(replacedFormat, 
            runs, // {0} is the number of runs 
            sec, // {1} is the elapsed time as float 
            frequency, // {2} is the call frequency as float 
            runs.ToString("N0", NumberFormat), // Expanded token {runs} is formatted with thousand separators 
            sec.ToString("F2", NumberFormat), // expanded token {time} is formatted as float in seconds with two digits precision 
            frequency.ToString("N0", NumberFormat)); // expanded token {frequency} is formatted as float with thousands separators 
      } 
      catch (FormatException ex) 
      { 
       throw new FormatException(
        String.Format("The input string format string did contain not an expected token like "+ 
           "{{runs}}/{{0}}, {{time}}/{{1}} or {{frequency}}/{{2}} or the format string " + 
           "itself was invalid: \"{0}\"", format), ex); 
      } 
     } 

     /// <summary> 
     /// Execute the given function n-times and print the timing values (number of runs, elapsed time, call frequency) 
     /// to the console window. 
     /// </summary> 
     /// <param name="func">Function to call in a for loop.</param> 
     /// <param name="runs">Number of iterations.</param> 
     /// <param name="format">Format string which can contain {runs} or {0},{time} or {1} and {frequency} or {2}.</param> 
     public static void Profile(this Action func, int runs, string format) 
     { 
      Func<int> f =() => 
      { 
       for (int i = 0; i < runs; i++) 
       { 
        func(); 
       } 
       return runs; 
      }; 
      f.Profile(format); 
     } 

     /// <summary> 
     /// Call a function in a for loop n-times. The first function call will be measured independently to measure 
     /// first call effects. 
     /// </summary> 
     /// <param name="func">Function to call in a loop.</param> 
     /// <param name="runs">Number of iterations.</param> 
     /// <param name="formatFirst">Format string for first function call performance.</param> 
     /// <param name="formatOther">Format string for subsequent function call performance.</param> 
     /// <remarks> 
     /// The format string can contain {runs} or {0},{time} or {1} and {frequency} or {2}. 
     /// </remarks> 
     public static void ProfileWithFirst(this Action func, int runs, string formatFirst, string formatOther) 
     { 
      func.Profile(1, formatFirst); 
      func.Profile(runs - 1, formatOther); 
     } 
    } 
} 
0

また、あなたが行うその後BenchmarkDotNet

を使用することができます。

1)を使用して、テストするコードを参照して、コンソールプロジェクトを作成します。

using BenchmarkDotNet.Running; 
using BenchmarkDotNet.Attributes; 
class Program 
{ 
    static void Main() 
    { 
     var summary = BenchmarkRunner.Run<YourBenchmarks>(); 
    } 
} 

public class YourBenchmarks 
{ 
    [Benchmark] 
    public object HideDataUsingAlgorithm() 
    { 
     return Namespace.hideDataUsingAlgorithm(); // call the code you want to benchmark here 
    } 
} 

2)リリースでビルドし、デバッガなしで実行します。

3)ビン/リリース/ YourBenchmarks-report-stackoverflow.md

レポートは、デフォルトでは中央値とSTDDEVが含まれている中でレポートを開きます。 BenchmarkDotNetはウォームアップを処理し、正確な統計情報を提供するためにプロセスを何度も起動します。

サンプルレポート:構成の

    Method |  Median | StdDev | 
----------------------- |------------ |---------- | 
HideDataUsingAlgorithm | 252.4869 ns | 8.0261 ns | 

docsをお読みください。

関連する問題