The QueryPerformanceCounter and QueryPerformanceFrequency functions in win32 are mainly used.
Document link: /zh-cn/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
class NanoSecondTimer { [DllImport("")] private static extern bool QueryPerformanceCounter(out long lpPerformanceCount); [DllImport("")] 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> /// Start timing /// </summary> public void Start() { (0); QueryPerformanceCounter(out startTime); } /// <summary> /// Stop timing /// </summary> public void Stop() { QueryPerformanceCounter(out stopTime); } /// <summary> /// Return the time elapsed time of the timer (unit: seconds) /// </summary> public double Duration { get { return (double)(stopTime - startTime) / (double)freq; } } }
QueryPerformanceFrequency This function will retrieve the frequency of the performance counter. The frequency of the performance counter is fixed at system startup and is consistent across all processors. Therefore, the results can be cached by simply querying the frequency when the application is initialized. On systems running Windows XP or later, the function will always succeed, so it will never return zero.
Here is the test code:
NanoSecondTimer nanoSecondTimer = new NanoSecondTimer(); (); for (int i = 0; i < 100000; i++) { i++; } (); double time = ;
This is the end of this article about C# timer class that is accurate to the nanosecond level. For more related C# timer content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!