如何使用C程序中的秒(时间)作为计数器?

如何使用C程序中的秒(时间)作为计数器?,c,loops,for-loop,clock,C,Loops,For Loop,Clock,我试图让一个C程序使用时钟的“秒”作为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<62

我试图让一个C程序使用时钟的“秒”作为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);
}
#包括
#包括
int main()
{
时钟开始,结束;
花费的时间加倍;
开始=时钟();
花费的时间=(双倍)开始/每秒时钟;

对于(time_-speed=0.0;time_-speed,很难准确地说出您想要做什么(根据对您的问题的评论),但我猜是这样的(循环将在5秒后终止)。请注意,clock()有点依赖于系统。有时是wallclock时间,但应该是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);
    }
#包括
#包括
int main()
{
时钟没有开始;
花费的时间加倍;
无符号整数i;
/*标记开始时间*/
开始=时钟();
对于(i=0;1;i++)
{
printf(“hello\n”);
/*获取循环启动后的CPU时间*/
花费的时间=(双倍)(时钟()-开始)/每秒时钟;
如果(花费的时间>=5.0)
打破
}
/*我可以想见,我的肚子会溢出来的*/
printf(“在5 CPU(?)秒内完成的迭代次数=%d.\n”,i);
返回(0);
}

您使用
(double)begin…
指定了
花费的时间
,然后在下面的
for
语句中重写它。另外,由于浮点值的内部舍入错误,检查
花费的时间==5.0
不是一个好主意。它可能永远不会精确命中
5.0
。您只是想循环吗(尽可能多次)直到某个时间段过去,还是在某个时间段内以特定间隔循环?