vapandris
vapandris

Reputation: 29

C: How to reset the reurn value of clock() to 0?

I'd like to know if there is a way to reset the return value of the clock() function to 0. I have a code something like this:

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

int main()
{
    /* clock_t t1; */
    unsigned int sec = 0;
    while(true) {
        if(clock() >= 1000) {
            printf("%u seconds has passed\r", sec);
            /* reset clock()'s return value to 0 */
            sec++;
        }
    }

    return 0;
}

what code should I put to the comment's place to reset the timer? Is there a way, or am I aproaching the problem in the incorrect manner?

Upvotes: 1

Views: 3085

Answers (2)

KamilCuk
KamilCuk

Reputation: 141060

clock() is always increasing.

The unit of clock is in CLOCKS_PER_SEC. One second has CLOCKS_PER_SEC clocks.

Note that clock() does not measure real time. clock() measures the processor time spend in your process. If you want to measure real time, use time() from time.h (or check your OS, on linux you can use clock_gettime(CLOCK_MONOTONIC, ...) or with CLOCK_REALTIME).

Save the current clock in a variable. Then compare the variable with current clock.

Usually stdout is line buffered. So until you write a newline character, nothing will show up. Make sure to flush stdout if you depend on that behavior.

#include <stdio.h>
#include <time.h>
int main() {
    unsigned int sec = 0;
    // we will stop the clock one second from now
    clock_t stopclock = clock() + 1 * CLOCKS_PER_SEC;
    while(1) {
        // current time is greater then the stopping time
        if (clock() > stopclock) {
            // increment stopping time by one second
            stopclock += 1 * CLOCKS_PER_SEC;
            printf("\r%u seconds has passed", sec);
            fflush(stdout);
            sec++;
        }
    }

    return 0;
}

Note: calculations on clock_t type like clock() + 1 * CLOCKS_PER_SEC can potentially overflow - great code would handle such corner cases.

Upvotes: 2

Dobrin Tinchev
Dobrin Tinchev

Reputation: 391

My best guess is that you are trying to time something Take a look at this

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

int main () {
   clock_t start_t, end_t, total_t;
   int i;

   start_t = clock();
   printf("Starting of the program, start_t = %ld\n", start_t);
    
   printf("Going to scan a big loop, start_t = %ld\n", start_t);
   for(i=0; i< 1000000000; i++) {
   }
   end_t = clock();
   printf("End of the big loop, end_t = %ld\n", end_t);
   
   total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
   printf("Total time taken by CPU: %f\n", total_t  );
   printf("Exiting of the program...\n");

   return(0);
}

Upvotes: 0

Related Questions