亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#精確到納秒級別的計時器類實現(xiàn)代碼

 更新時間:2021年08月21日 11:03:21   作者:晨晞gg  
這篇文章主要介紹了C#精確到納秒級別的計時器類,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

主要用到了win32里面的QueryPerformanceCounter和QueryPerformanceFrequency兩個函數(shù)

文檔鏈接: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>
        ///  返回計時器經(jīng)過時間(單位:秒)
        /// </summary>
        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double)freq;
            }
        }
    }

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

下面是測試代碼:

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

到此這篇關于C#精確到納秒級別的計時器類的文章就介紹到這了,更多相關C#計時器類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論