0

我正在尝试让 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);
}
4

1 回答 1

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);
    }
于 2013-09-30T03:07:06.173 回答