【问题标题】:How to use seconds (time) in C program as a counter?如何在C程序中使用秒(时间)作为计数器?
【发布时间】:2013-09-29 23:44:02
【问题描述】:

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

【问题讨论】:

  • 您使用(double)begin... 分配了time_spent,然后在您的以下for 语句中覆盖了它。由于浮点值的内部舍入错误,检查time_spent == 5.0 也不是一个好主意。它可能永远不会准确命中5.0
  • 您是想循环(尽可能多地)直到经过一定的时间,还是以特定的间隔循环一定的时间?

标签: c loops for-loop clock


【解决方案1】:

很难确切地说出您想要做什么(根据您对问题提出的 cmets),但我猜它是这样的(循环将在 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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2012-10-11
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多