时钟功能usleep在c程序中无法正常工作?

时间:2016-06-14 21:32:41

标签: c clock

我想使用clock_t类型延迟我的程序500毫秒。例如我有以下代码:

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

int main()
{
   clock_t start_t, end_t, total_t,start_2,end_2,total_2;
   int i;

   start_t = clock();
   printf("start_t = %ld\n", start_t);

   //do a loop
   for(i=0; i< 10000000; i++)
   {
   }

   end_t = clock();


   printf("end_t = %ld \n", end_t);

   total_t = (double)(end_t - start_t)*1000 / CLOCKS_PER_SEC;
   printf("Total1 in msec %ld \n",total_t);



   start_2=clock();
   printf("start_2 %ld\n ", start_2);
   usleep(500000);

   end_2=clock();
   printf("end_2 %ld\n ", end_2);
   total_2=(double)(start_2-end_2)*1000/CLOCKS_PER_SEC;
   printf("Total2 in msec %ld\n ", total_2);


   return(0);
}

我发现usleep的值为μsec作为输入。所以我把500000。

但我明白了:

start_t = 1041
end_t = 50441 
Total1 in msec 49 

start_2 50446
end_2 50478
Total2 in msec 0

出了什么问题?为什么total2 = 0?有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

实际上,时钟功能记录了此进程的cpu周期数。当您调用usleep函数时,cpu将不会为此过程提供任何时间幻灯片。 所以真正的原因是clock()函数。也许你可以找到一些函数来获得系统时间。我认为它会奏效。

答案 1 :(得分:0)

找到解决方案。我写了一个延迟函数:

void delay (unsigned int msecs) {
clock_t goal = msecs*CLOCKS_PER_SEC/1000 + clock();  //convert msecs to clock count  
while ( goal > clock() );               // Loop until it arrives.

}