在C中使用计时器的方法是什么?我需要等到500毫秒才能找到工作.请提及做这项工作的任何好方法.我用过sleep(3);但是这个方法在那段时间内没有做任何工作.我有一些东西会尝试,直到那个时间来获得任何输入.
Dav*_*yon 10
这是我使用的解决方案(它需要#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);
Run Code Online (Sandbox Code Playgroud)