C#精確到納秒級別的計時器類實現代碼

主要用到瞭win32裡面的QueryPerformanceCounter和QueryPerformanceFrequency兩個函數

文檔鏈接:https://docs.microsoft.com/zh-cn/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter

class NanoSecondTimer
    {

        [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 NanoSecondTimer()
        {
            startTime = 0;
            stopTime = 0;
            if (QueryPerformanceFrequency(out freq) == false)
            {
                throw new Win32Exception();
            }
        }

        /// <summary>
        /// 開始計時
        /// </summary>
        public void Start()
        {
            Thread.Sleep(0);
            QueryPerformanceCounter(out startTime);
        }

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

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

QueryPerformanceFrequency這個函數會檢索性能計數器的頻率。性能計數器的頻率在系統啟動時是固定的,並且在所有處理器上都是一致的。因此,隻需在應用初始化時查詢頻率,即可緩存結果。在運行 Windows XP 或更高版本的系統上,該函數將始終成功,因此永遠不會返回零。

下面是測試代碼:

NanoSecondTimer nanoSecondTimer = new NanoSecondTimer();
            nanoSecondTimer.Start();
            for (int i = 0; i < 100000; i++)
            {
                i++;
            }
            nanoSecondTimer.Stop();
            double time = nanoSecondTimer.Duration;

到此這篇關於C#精確到納秒級別的計時器類的文章就介紹到這瞭,更多相關C#計時器類內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: