我试图了解在线程中执行某些代码需要花费多少时间。但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 同步编码音频需要多少时间。
最佳答案
我认为问题在于您正在使用clock()函数。
时钟函数确定自调用进程以来所使用的处理器时间量,以每秒 CLOCKS_PER_SEC 为单位测量。
例如:
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 秒的计数,因为代码一直在使用处理器。
关于Clock() 在具有更多命令的 usleep 循环中返回值 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12511540/