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日

相关推荐
Rocky4012 天前
JavaEE->多线程:定时器
java·开发语言·多线程·定时器
Rocky4013 天前
javaEE->多线程:线程池
java·运维·服务器·线程池·多线程·定时器
让我们一起加油好吗4 天前
【基础算法】高精度(加、减、乘、除)
c++·算法·高精度·洛谷
ItJavawfc21 天前
驱动-Linux定时-timer_list
驱动开发·定时器·驱动定时器·timer_list
Terasic友晶科技1 个月前
第20篇:Linux设备驱动程序入门<七>
fpga开发·定时器·de1-soc开发板·linux设备驱动程序
憧憬一下1 个月前
stm32之TIM定时中断详解
stm32·单片机·嵌入式·定时器
callJJ1 个月前
阻塞队列的介绍和简单实现——多线程编程简单案例[多线程编程篇(4)]
java·开发语言·数据结构·java-ee·多线程编程·定时器·阻塞队列
beyond谚语2 个月前
七、Qt框架编写的多线程应用程序
c++·qt·多线程·定时器
Wx120不知道取啥名2 个月前
基于MCU实现的电机转速精确控制方案:软件设计与实现
单片机·嵌入式硬件·定时器·adc·中断·电机控制·软件方案
Ronin-Lotus3 个月前
嵌入式硬件篇---PWM输出通道&定时器
stm32·单片机·嵌入式硬件·c·定时器·pwm