HowTo:C#效能測試擴充函數

來源:互聯網
上載者:User

看了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 // 平均已耗用時間                                );   }   }

有了這個擴充方法,你就可以對某些特定的方法自動調用效能函數了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.