Clock() 在具有更多命令的 usleep 循环中返回值 0

标签 c clock usleep

我试图了解在线程中执行某些代码需要花费多少时间。但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/

相关文章:

iphone - 如何在我们的应用程序中创建不时旋转的模拟时钟

c - 如何在 pthread 函数 usleep() 的 for 循环中使用随机种子生成器?

c - 使用 void * 写入硬件寄存器

c - 将压缩行存储写入文本文件的标准格式?

java - if 和 else 语句 Java 试图停止一条语句

java - 如何将 java.sql.Timestamp 格式化为 (hh :mm AM/PM)

c - fork 和 usleep 错误

c - float 和usleep问题

c - 多种资源的细粒度锁定算法

c# - 从 C 函数返回结构,C# 中的等价物是什么?