C# 效能分析計時器

來源:互聯網
上載者:User

第一種方法:使用Stopwatch

Code
class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();          

            for (int i = 0; i < 11031400; i++)
            {
                InternalMethod();
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds.ToString());

       }

    private static void InternalMethod()
        {
        }

}

上面的代碼重

 複調用了方法100多萬次,花的時間是7MS左右。而如果把for裡的方法調用去掉,則只需要3MS左右,也就是說100多萬次的調用要花費5MS左右的時間。             

for (int i = 0; i < 1103140; i++)
  {              
   // InternalMethod();          
  }  如果把for增加到1億次,則需要500多MS。

第二種方法:使用Environment.TickCount

Code
class Program
    {
        static void Main(string[] args)
        {
            long vTickCount = Environment.TickCount; //作業系統啟動經過的毫秒數 即開機的時間

            for (int i = 0; i < 1103140; i++)
            {
                //InternalMethod();
            }        

            Console.WriteLine(Environment.TickCount - vTickCount);
        }
    }

第三種方法:高效能精確測量:Win32 API 使用QueryPerformanceCounter() 和 QueryPerformanceFrequency() 方法支援高精度計時。

       這些方法,比“標準的”毫秒精度的計時方法如 GetTickCount() 之類有高得多的精度。另一方面來說,在 C# 中使用“非託管”的 API 函數會有一定的開銷,但比起使用一點都不精確的 GetTickCount() API 函數來說要好得多了。 

第一個函數 QueryPerformanceCounter() 查詢任意時刻高精度計數器的實際值。第二個函數 QueryPerformanceFrequency() 返回高精度計數器每秒的計數值。為了獲得某一程式碼片段經曆的時間,你需要獲得程式碼片段開始前和結束後這兩個計時時刻的高精度計數器實際值。這兩個值的差指出了程式碼片段執行所經曆的時間。

然後通過將差除以每秒計數值(高精度計時器頻率),就可以計算經過的時間了。

duration = (stop - start) / frequency
經過時間 = (停止時間 - 開始時間) / 頻率

需要關於 QueryPerformanceCounter 和 QueryPerformanceFrequency 的更多資訊,請參閱 MSDN 文檔。

下面的類實現了 QueryPerformanceCounter() 和 QueryPerformanceFrequency() API 函數的功能.

Code
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Win32
{
    internal class HiPerfTimer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(
            out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(
            out long lpFrequency);

        private long startTime, stopTime;
        private long freq;

        // 建構函式
        public HiPerfTimer()
        {
            startTime = 0;
            stopTime  = 0;

            if (QueryPerformanceFrequency(out freq) == false)
            {
                // 不支援高效能計數器
                throw new Win32Exception();
            }
        }

        // 開始計時器
        public void Start()
        {
            // 來讓等待線程工作
            Thread.Sleep(0);

            QueryPerformanceCounter(out startTime);
        }

        // 停止計時器
        public void Stop()
        {
            QueryPerformanceCounter(out stopTime);
        }

        // 返回計時器經過時間(單位:秒)
        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double) freq;
            }
        }
    }
}

 

使用這個類很簡單。只需要建立一個 HiPerfTimer 的執行個體,然後調用 Start() 開始計時,Stop() 停止計時。要獲得經過的時間,調用 Duration() 函數即可。

參考下面的例子。

HiPerfTimer pt = new HiPerfTimer();     // 建立新的 HiPerfTimer 對象
pt.Start();                             // 啟動計時器
Console.WriteLine("Test\n");            // 需要計時的代碼
pt.Stop();                              // 停止計時器
Console.WriteLine("Duration: {0} sec\n", pt.Duration); // 列印需要計時部分代碼的用時

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.