看了ark的文章讓我想起了些這個。可能沒有太多的實際意義,但確是一個不錯的思路。
我們平時在使用stopwatch統計時間的時候一般會這樣使用。
Stopwatch watch = Stopwatch.StartNew();for (int i = 0; i < runs; i++){.......}watch.Stop();
這樣就可以統計到啟動並執行時間,但用過Python的人都知道,python自備電池。那麼其實用擴充函數就可以實現這個類似功能(PS:其實功能還是相差蠻大的,但皮已經畫的很像了)。
先示範如何使用(統計A.Run這個方法運行100次的使用時間)
class Program { static void Main(string[] args) { A a = new A(); Action act = a.Run; Console.WriteLine(act.Profile(100)); Console.Read(); } } public class A { public void Run() { for (int i =0; i < 100000; i++) ; } }}
用擴充方法來實現這個需求,這樣就不用重複寫stopwatch了
public static class FunctionHelper { public static string Profile(this Action func, int runs) { Stopwatch watch = Stopwatch.StartNew(); for (int i = 0; i < runs; i++) { func(); } watch.Stop(); float sec = watch.ElapsedMilliseconds / 1000.0f; float freq = runs / sec; return String.Format("execute runs:{0};sec:{1};freq", runs, //運行次數 sec, // 已耗用時間 freq // 平均已耗用時間 ); } }
有了這個擴充方法,你就可以對某些特定的方法自動調用效能函數了。