2013-04-21 54 views
9

我正在爲我的大學制作一個圖像隱寫術項目。我已經完成了這個項目,並保留了幾種不同的算法來隱藏圖像中的數據。查找方法的執行時間

我想問的是,在C#中,我可以通過它找到程序中兩點之間的執行/運行時間。 例如

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

我想這樣做,以顯示簡單(耗時更少)和更有效的,但耗時的算法之間的差異(使用相同的數據和相同的圖像)。我對Color和GrayScale Images有大約10種不同的算法。

沒有多線程,所以不會是一個問題。 Theres只是一個主線程。

+0

的可能的複製[測量代碼執行時間(https://stackoverflow.com/questions/16376191/measuring-code-execution-time) - 這是老了幾天,但【注意事項】(HTTPS:/ /meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled/),「*一般規則是保留問題的最佳答案集合,並關閉另一個作爲重複*「 – ruffin 2017-10-31 15:48:52

回答

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)打開是在bin /發行/ YourBenchmarks-report-stackoverflow.md

該報告包含中位數和STDDEV默認的報告。 BenchmarkDotNet負責熱身並啓動該過程多次以提供準確的統計數據。

報告示例:

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

對於配置讀取docs