How to use timer in C?

后端 未结 4 1340
梦谈多话
梦谈多话 2020-11-30 14:13

What is the method to use a timer in C? I need to wait until 500 ms for a job. Please mention any good way to do this job. I used sleep(3); But this method does

4条回答
  •  一个人的身影
    2020-11-30 14:25

    Here's a solution I used (it needs #include ):

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

提交回复
热议问题