我试图让一个C程序使用来自clock_t的“秒”作为for循环计数器。这怎么可能?以下是我的编码无效,
#include<stdio.h>
#include <time.h>
int main()
{
clock_t begin, end;
double time_spent;
begin = clock();
time_spent = (double)begin / CLOCKS_PER_SEC;
for(time_spent=0.0; time_spent<62000.0; time_spent++)
{
printf("hello \n");
if(time_spent==5.0)
break;
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf(" %lf\n", time_spent);
}
答案 0 :(得分:2)
很难确切地说出你想要做什么(根据对你的问题的评论),但我猜它是这样的(循环将在5秒后终止)。请注意,clock()在某种程度上取决于系统。有时它是挂钟时间,但它应该是CPU时间。
#include <stdio.h>
#include <time.h>
int main()
{
clock_t begin;
double time_spent;
unsigned int i;
/* Mark beginning time */
begin = clock();
for (i=0;1;i++)
{
printf("hello\n");
/* Get CPU time since loop started */
time_spent = (double)(clock() - begin) / CLOCKS_PER_SEC;
if (time_spent>=5.0)
break;
}
/* i could conceivably overflow */
printf("Number of iterations completed in 5 CPU(?) seconds = %d.\n",i);
return(0);
}