Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to make a timer in C Programming?

+1 vote
asked Nov 25, 2020 by Superman365 (570 points)

Hope for a quick answer

Can we make a timer that will repeat forever and keep going? I want it to go like:

Please type the seconds and minutes:(Hrs:mins:secs)

(Then the countdown)

(After countdown:)

Countdown complete!

1 Answer

+1 vote
answered Nov 25, 2020 by Peter Minarik (101,340 points)
edited Nov 26, 2020 by Peter Minarik

Code Snippet

Have a look at this: https://stackoverflow.com/questions/17167949/how-to-use-timer-in-c

Update

I've turned the code snippet into a working program:
#include <time.h>
#include <stdio.h>

int main () 
{
    int iterations = 0;
    int msec = 0, trigger = 10; /* 10ms */
    clock_t before = clock ();
    do
    {
        printf("doing some heavy work here...\n");
        for (int i = 0; i < 1000000; i++) /* no operation */;
        /* Do something to busy the CPU just here while you drink a coffee
         * Be sure this code will not take more than `trigger` ms */
        clock_t difference = clock () - before;
        msec = difference * 1000 / CLOCKS_PER_SEC;
        iterations++;
    } while (msec < trigger);

    printf ("Time taken %d seconds %d milliseconds (%d iterations)\n", msec / 1000, msec % 1000, iterations);
    return 0;
}
commented Nov 25, 2020 by Superman365 (570 points)
It is showing incorrect. I mean there are errors.
commented Nov 26, 2020 by Peter Minarik (101,340 points)
What I linked was just a code snippet, not a fully working program. It is just a fragment of code. It still needs to be put into a function, have the right header files included, etc.
commented Nov 26, 2020 by Superman365 (570 points)
Oh! Ok. I get it now. But I am beginner. So I need the whole code.
commented Dec 16, 2025 by jtreacy1013 (210 points)
I got mine to work.  the include<ctime> has granularity to the nearest second and the only timer mentioned in the D.S.Malik text C++Programming - 8th edition published by Cengage).

This one is superior as goes to the milisecond (second / 1000).  Thanks and this does indeed help.
commented Dec 17, 2025 by Peter Minarik (101,340 points)
I'm glad this was useful for you.

Happy coding!
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...