Clock()返回usleep循环中的值0,命令数更多
我想看看在一个线程中执行一些代码需要多少时间。但是clock()返回0 代码如下:Clock()返回usleep循环中的值0,命令数更多,c,clock,usleep,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(
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;
}
intmain(intargc,char*argv[])
{
int开始,结束;
浮动时间;
时钟i,j;
结构时间值tv1;
结构时间值tv2;
对于(i=0;i我认为问题在于您使用的是clock()函数
时钟函数确定自调用进程以来使用的处理器时间量,以每秒时钟为单位。
例如:
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);
longi;
时钟启动=时钟();
对于(i=0;i<100000000;++i)
exp(log((double)i));
时钟完成=时钟();
printf(“执行for循环花费了%d秒。\n”,
(完成-开始)/时钟(每秒);
将给您8秒的计数,因为代码一直使用处理器。如果您需要高精度计时,则时钟
不是最佳选择。相反,您必须使用更多特定于平台的功能。man 3 clock—“时钟()函数返回程序使用的处理器时间的近似值。“使用延迟执行时,程序不使用处理器。