时间:2022-05-18 08:42:21 | 栏目:.NET代码 | 点击:次
主要用到了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;