【问题标题】:c clock() in different OSc时钟()在不同的操作系统
【发布时间】:2021-04-06 20:00:30
【问题描述】:

我需要一个 60HZ 定时器(16.6 毫秒触发一次)

它在 windows(mingw gcc) 中运行良好,但在 liunx(gcc) 中运行良好

谁能帮我解决这个问题?谢了

#include <stdio.h>
#include <time.h>t
#define PRE_MS CLOCKS_PER_SEC / 1000
int main()
{
    clock_t pre = clock();
    int cnt = 0;
    printf("CLOCKS_PER_SEC = %d\n", CLOCKS_PER_SEC);
    while (1)
    {
        clock_t diff = clock() - pre;
        if (diff > 16 * PRE_MS)
        {
            cnt++;
            if (cnt > 60)
            {
                printf("%d\n", (int)pre);
                cnt = 0;
            }
            pre += diff;
        }
    }
}
  • windows 中的 printf pre 1s
CLOCKS_PER_SEC = 1000
1020
2058
3095
4132
5169
6206
7243
8280
9317
  • linux 中的 printf pre 2s
CLOCKS_PER_SEC = 1000000
1875000
3781250
5687500
7593750
9500000
11406250
13312500
15218750

【问题讨论】:

  • 请不要在发布答案后更改代码。
  • 仍然是这个问题,我只是想让我的代码更干净,你的代码似乎对我有用,我稍后会检查它,thx

标签: c clock


【解决方案1】:

首先是一个误解:60 Hz 不是每秒 17 次操作,而是 60。

第二个周期检查读取clock() 两次并丢弃任何时间间隔以调用printf()。 AFAIK CLOCKS_PER_SEC 在 Linux 上比在 Windows 系统上更大,因此您更有可能“丢弃”时钟滴答声。阅读clock()一次,例如:

#include <stdio.h>
#include <time.h>

int main(void)
{
    unsigned long long tickcount = 0;
    clock_t baseticks = clock();    
    while (tickcount < 180) {           // for 3 seconds
        tickcount++;
        clock_t nexttick = (clock_t) (baseticks + tickcount * CLOCKS_PER_SEC / 60);
        while(clock() < nexttick) {}    // wait
        printf("Tick %llu\n", tickcount);
    }
    return 0;
}

代码从总经过时间开始计算,因此任何不是精确时钟滴答数的间隔都会被平均化(而不是累积的舍入误差)。

在某些时候来自clock() 的值会溢出/换行,因此运行任何时间长度的实际实现都必须处理这个问题。

【讨论】:

    猜你喜欢
    • 2014-10-09
    • 2014-10-22
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多