注册 登录
编程论坛 C++教室

一个微秒级定时循环的问题,想知道误差会出在那一段代码中?

Lyone 发布于 2011-03-28 14:54, 413 次点击
程序代码:
    QueryPerformanceFrequency(pFrquency);//获得CPU的值。
    pSleepCount->QuadPart = pFrquency->QuadPart*SleepMSTime;//SleepMSTime是每次循环希望间隔的时间,单位是毫秒
    LARGE_INTEGER StartCount,DoingCount;
    LONG Times = 0;
    QueryPerformanceCounter(&StartCount);
    for (;;)
    {
        Doing();//自定义的一段程序
        Times++;
        do
        {
            QueryPerformanceCounter(&DoingCount);
        } while ((DoingCount.QuadPart-StartCount.QuadPart)*1000 < pSleepCount->QuadPart*Times);      
    }
用实例测下来。SleepMSTime越大,误差也越大。我自己分析了一下。SleepMSTime的变化,最大的影响应该是do...while这段吧?可是我已经用到了Times这个标志数,来判断当前时间DoingCount与最初StartCount的差了呀?为什么还会有误差呢?

[ 本帖最后由 Lyone 于 2011-3-28 15:10 编辑 ]
3 回复
#2
Lyone2011-03-29 09:14
顶起来
#3
rjsp2011-03-29 11:18
"用实例测下来。SleepMSTime越大,误差也越大。"
--- 那你就应该给出你的数据。反正我没发现“SleepMSTime越大,误差也越大”

我的数据:SleepMSTime=1000
0.000214
1000.000011
2000.000041
3000.000079
4000.000157
5000.000034
6000.000176
7000.000172
8000.000086
9000.000022
10000.000082
11000.000049
12000.000034

SleepMSTime=10000
0.000375
10000.000071
20000.000161
30000.000071
40000.000000
50000.000034
60000.000191
70000.000049
80000.000161
90000.000206
100000.000086
110000.000180
120000.000124

而重要的是,你就不能贴个完整的,别人可以编译的代码吗?
程序代码:
#include <windows.h>
#include <stdio.h>

int main()
{
    long long SleepMSTime = 10000; // 毫秒

    LARGE_INTEGER frquency;
    QueryPerformanceFrequency( &frquency );
   

    LARGE_INTEGER StartCount, DoingCount;
    QueryPerformanceCounter( &StartCount );
    DoingCount = StartCount;
    for( long long Times=0; Times<100; ++Times )
    {
        for( ; QueryPerformanceCounter(&DoingCount), (DoingCount.QuadPart-StartCount.QuadPart)*1000<frquency.QuadPart*SleepMSTime*Times; );

        //Doing();
        
//printf( "%lld\n", DoingCount.QuadPart*1000/frquency.QuadPart );
        printf( "%lf\n", (DoingCount.QuadPart-StartCount.QuadPart)*1000.0/frquency.QuadPart );
    }

    return 0;
}

#4
Lyone2011-03-29 15:24
回复 3楼 rjsp
我找到我这个程序的问题了。是测试的时候显示的内容没有同步。

谢谢你的指教,和那个测试的程序段。下次我一定注意。把测试程序贴全了。
1