C#精確到納秒級別的計時器類實現(xiàn)代碼
主要用到了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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#簡單實現(xiàn)在網(wǎng)頁上發(fā)郵件的案例
本文分享一個C#利用SMTP發(fā)送郵件的案例,提供了前后臺代碼,方便大家學習。2016-03-03