0

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);
}
Gravity M
  • 1,485
  • 5
  • 16
  • 28
  • 1
    You assigned `time_spent` using `(double)begin...` and then overwrote it in your following `for` statement. Also the check `time_spent == 5.0` is not a good idea due to internal rounding errors for floating point values. It may never hit exactly `5.0`. – lurker Sep 29 '13 at 23:49
  • Are you just trying to loop (as many times as possible) until a certain amount of time has passed, or to loop at specific intervals for a certain amount of time? – Dmitri Sep 30 '13 at 02:08

1 Answers1

2

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);
    }
willus
  • 501
  • 3
  • 7