我试图看看在线程中执行某些代码需要多少时间。但是 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 %dn", 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|%dn",begin,end, time_spent,CLOCKS_PER_SEC);
}
return 0;
}
但是我一直得到0次点击。我认为 usleep 并没有完全等待 200 毫秒,所以我需要计算函数使用 ffmpeg 对音频进行编码和同步所花费的时间。
问题是你正在使用 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 秒的计数,因为代码一直在使用处理器。