3

我想看看在一个线程中执行一些代码需要多少时间。但是clock()返回0。

这是代码:

int main(int argc, char *argv[])
{

int begin, end;
float time_spent;

clock_t i,j;
struct timeval tv1;
struct timeval tv2;

for(i = 0; i<6; i++)
{

begin = clock();

// Send Audio Data
....

gettimeofday(&tv1,NULL);

usleep(200000);   // Wait 200 ms

gettimeofday(&tv2,NULL);

printf("GETTIMEOFDAY %d\n", tv2.tv_usec-tv1.tv_usec);  // Time using date WORKING

end = clock() - begin;

// Store time
...


printf ("It took me %d clicks (%f seconds).\n",begin,((float)begin)/CLOCKS_PER_SEC);
printf ("It took me %d clicks (%f seconds).\n",end,((float)end)/CLOCKS_PER_SEC);

time_spent = (((float)end) * 1000.0 / ((float)CLOCKS_PER_SEC)); // Time using clock BAD

printf("\n TIME %dms|%dms|%fms|%d\n",begin,end, time_spent,CLOCKS_PER_SEC);

}



return 0;
}

但我一直得到 0 次点击。我认为 usleep 并没有准确地等待 200 毫秒,所以我需要计算使用 ffmpeg 同步编码音频的函数花费了多少时间。

4

1 回答 1

3

我认为问题在于您正在使用 clock() 函数。

The clock function determines the amount of processor time used since the invocation of the calling process, measured in CLOCKS_PER_SEC of a second.

例如:

clock_t start = clock();
sleep(8);
clock_t finish = clock();
printf("It took %d seconds to execute the for loop.\n",
  (finish - start) / CLOCKS_PER_SEC);

这段代码会给你一个 0 的值。因为代码没有使用处理器,所以它正在休眠。然而,这段代码:

long i;
clock_t start = clock();
for (i = 0; i < 100000000; ++i)
  exp(log((double)i));
clock_t finish = clock();
printf("It took %d seconds to execute the for loop.\n",
  (finish - start) / CLOCKS_PER_SEC);

会给你 8 秒的计数,因为代码一直在使用处理器。

于 2012-09-20T11:37:29.703 回答