如何在C程序中使用秒(时间)作为计数器? [英] How to use seconds (time) in C program as a counter?

查看:93
本文介绍了如何在C程序中使用秒(时间)作为计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让C程序使用clock_t中的秒"作为for循环计数器.这怎么可能?下面是我的编码不起作用,

I am trying to get a C program to use "seconds" from clock_t as a for loop counter. How is it possible? Below is my coding which is not working,

#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);
}

推荐答案

很难确切地说出您想做什么(根据对问题的评论),但是我猜想是这样的(循环将终止5秒后).请注意,clock()在某种程度上取决于系统.有时是挂钟时间,但应该是CPU时间.

It's hard to tell exactly what you want to do (per the comments made to your question), but I'm guessing it's something like this (loop will terminate after 5 seconds). Note that clock() is somewhat system dependent. Sometimes it is wallclock time, but it is supposed to be CPU time.

#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);
    }

这篇关于如何在C程序中使用秒(时间)作为计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆