Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
时钟函数usleep在c程序中工作不正常?_C_Clock - Fatal编程技术网

时钟函数usleep在c程序中工作不正常?

时钟函数usleep在c程序中工作不正常?,c,clock,C,Clock,我想使用时钟类型将程序延迟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);

我想使用时钟类型将程序延迟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);
}

出了什么问题?为什么total2=0?需要帮忙吗

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

找到了解决办法。我写了一个延迟函数:

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.

}

“clock()函数决定处理器使用的时间量…”当您睡眠时,时间会流逝,但不使用处理器时间。那么我需要delay()函数吗?不,您需要使用其他函数来测量墙壁时间。在MAC电脑上,使用
mach\u absolute\u time
。在Windows上是
QueryPerformanceCounter
。在linux上是??只需使用不同的函数来延迟或测量时间?在linux上,我认为您必须使用
gettimeofday
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.