C#实现纳秒级的计时器功能

常用的 Windows API 方法 GetTickCount() 返回系统启动后经过的毫秒数。另一方面,GetTickCount() 函数仅有 1ms 的分辨精度,精度也很不好。

我们要另外寻找一种方法来精确测量时间。

Win32 API 使用 QueryPerformanceCounter() 和 QueryPerformanceFrequency() 方法支持高精度计时。这些方法,比"标准的"毫秒精度的计时方法如 GetTickCount() 之类有高得多的精度。

虽然在 C# 中使用"非托管"的 API 函数会有一定的开销,但比起使用一点都不精确的 GetTickCount() API 函数来说要好得多了。

下面的类实现了 QueryPerformanceCounter() 和 QueryPerformanceFrequency() API 函数功能的封装。

代码封装

cs 复制代码
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Win32
{
    internal class HighTimer
    {
        [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 HighTimer()
        {
            startTime = 0;
            stopTime = 0;

            if (QueryPerformanceFrequency(out freq) == false)
            {
                // 不支持高性能计数器
                throw new Win32Exception();
            }
        }

        // 开始计时器
        public void Start()
        {
            // 来让等待线程工作
            Thread.Sleep(0);
            QueryPerformanceCounter(out startTime);
        }

        // 停止计时器
        public void Stop()
        {
            QueryPerformanceCounter(out stopTime);
        }

        // 返回计时器经过时间(单位:秒)
        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double)freq;
            }
        }
    }
}

调用方法

cs 复制代码
HighTimer pt = new HighTimer();    // 创建新的 HighTimer 对象
pt.Start();                         // 启动计时器
Console.WriteLine("Test/n");        // 需要计时的代码
pt.Stop();                          // 停止计时器
Console.WriteLine("Duration: {0} sec/n", pt.Duration); // 打印需要计时部分代码的用时

参考链接

https://mp.weixin.qq.com/s/xIRvgT8HSB0RKOhWV___zQ

特此记录

anlog

2024年5月28日

相关推荐
CUC-MenG3 天前
2025杭电多校第八场 最有节目效果的一集、最自律的松鼠、最甜的小情侣、最努力的活着 个人题解
数学·线段树·高精度·模拟·dp·红黑树·线性dp·平衡树·线段树维护矩阵
四谎真好看13 天前
第六章第二节 定时器定时中断 & 定时器外部时钟
stm32·单片机·嵌入式硬件·定时器·timer
DIY机器人工房16 天前
【科普】在STM32中有哪些定时器?
c语言·嵌入式·定时器·diy机器人工房
深圳市尚想信息技术有限公司1 个月前
华大北斗TAU1201-1216A00高精度双频GNSS定位模块 自动驾驶专用
高精度·电源管理·华大北斗·gnss定位模块·定位模块
憧憬一下2 个月前
FreeRTOS定时器
嵌入式·freertos·定时器
Rocky4012 个月前
JavaEE->多线程:定时器
java·开发语言·多线程·定时器
Rocky4012 个月前
javaEE->多线程:线程池
java·运维·服务器·线程池·多线程·定时器
让我们一起加油好吗2 个月前
【基础算法】高精度(加、减、乘、除)
c++·算法·高精度·洛谷
ItJavawfc3 个月前
驱动-Linux定时-timer_list
驱动开发·定时器·驱动定时器·timer_list
Terasic友晶科技3 个月前
第20篇:Linux设备驱动程序入门<七>
fpga开发·定时器·de1-soc开发板·linux设备驱动程序