1

Using difftime for loop parameters

 2 years ago
source link: https://www.codesd.com/item/using-difftime-for-loop-parameters.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Using difftime for loop parameters

advertisements

I am trying to create a loop function based on the time. After the iteration, it will print every 60 second "60 second passed". But this code result me in couple of "60 second passed" while actually me watch does not even showing 1 minute already.. I tried below, but I am expecting it to show me this information, but it does not (only the first couple of lines of iteration. afterwards not..)

Can anyone help in this matter? Thank you

#include <stdio.h>
#include <time.h>

int main()
{
time_t start,stop;
start = time(NULL);
time(&start);
int iteration, i;
    for (iteration = 1; iteration <= 500; iteration++) {
            for (i = 0; i <= 50; i++) {
                     printf("looping while waiting 60 second..\n");

             }
            stop = time(NULL);
            int diff = difftime(start, stop);
            if (diff % 60 == 0) {
                     printf("60 second passed..");}
            }

    return 1;
}


difftime and the following code are likely being executed multiple times before even one second has passed. As a result, difftime will return a value < 1, which is truncated to 0 by your implicit cast. And of course 0 % 60 == 0.

EDIT:

You might consider something like:

start = time(NULL);
for(; /* some condition that takes forever to meet */;) {
    // do stuff that apparently takes forever.
    stop = time(NULL);
    double diff = difftime(stop, start);
    if (diff >= 60) {
        printf("60 seconds passed...");
        start = time(NULL);
    }
}

Also note that in your example code, start and stop should be flipped in the call to difftime.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK