C#用QueryPerformanceCounter()实现精确定时器

      原来Sleep()的精度根本不够毫秒级别啊,弄了好长时间。最终还是用QueryPerformanceCounter()写了延时程序,把自己的一点小成果记下来吧呵呵。

很简单的原理,可是还是搞了半天。希望有大虾们指点指点。

       

        //调用API函数
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceCounter(ref long x);
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceFrequency(ref long x);
        //定义延迟函数
        public void delay(long delay_Time)
        {
           
            long stop_Value = 0;
            long start_Value = 0;
            long freq = 0;
            long n =0;
           
            QueryPerformanceFrequency(ref freq);  //获取CPU频率
            long count = delay_Time * freq / 1000;
            QueryPerformanceCounter(ref start_Value); //获取初始前值
           
            while ( n<count) //不能精确判定
            {
                QueryPerformanceCounter(ref stop_Value);//获取终止变量值
                n = stop_Value - start_Value;               
            }

转载于:https://www.cnblogs.com/liuchao1009/archive/2010/12/22/1914131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值