gpt4 book ai didi

c - 如何在 C 中使用定时器?

转载 作者:太空狗 更新时间:2023-10-29 16:58:29 24 4
gpt4 key购买 nike

C语言中定时器的使用方法是什么?我需要等到 500 毫秒才能找到工作。请提及完成这项工作的任何好方法。我使用了 sleep(3); 但是这个方法在这段时间内没有做任何工作。我有一些东西会尝试直到那个时候得到任何输入。

最佳答案

这是我使用的解决方案(它需要 #include <time.h> ):

int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();

do {
/*
* Do something to busy the CPU just here while you drink a coffee
* Be sure this code will not take more than `trigger` ms
*/

clock_t difference = clock() - before;
msec = difference * 1000 / CLOCKS_PER_SEC;
iterations++;
} while ( msec < trigger );

printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
msec/1000, msec%1000, iterations);

关于c - 如何在 C 中使用定时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17167949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com