如何在C中使用计时器?

8 c timer countdowntimer

在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)

  • @mLstudent33`这个宏是时钟函数测量的每秒时钟滴答数`[来源](https://www.gnu.org/software/libc/manual/html_node/CPU-Time.html) (2认同)

小智 8

您可以使用time.h中time_t结构和clock()函数.

time_t通过使用clock()并在结构中存储开始时间,并通过比较存储时间和当前时间之间的差异来检查已用时间.