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.

clock() function does not work.

+6 votes
asked Jun 22, 2023 by Alexander Urezchenko (190 points)

This code should print internal time every second. But it does not work. Why?

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

int main()
{
    long int lastTime=clock();
    while(1==1){
        if (lastTime < clock()-1000){ 
            lastTime = clock();
            printf ("internal clock = %d\n", clock());
        }
    }    return 0;
}

2 Answers

+1 vote
answered Jun 28, 2023 by Peter Minarik (89,230 points)
edited Jun 28, 2023 by Peter Minarik

The clock() function does not return time in milliseconds, as you assumed. To get the time measured in milliseconds, you need to divide the returned value by CLOCKS_PER_SEC.

I've fixed up your code and added some improvements:

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

int main()
{
    clock_t nextTick = clock() + CLOCKS_PER_SEC;
    while (1)
    {
        clock_t timeNow = clock();
        if (nextTick <= timeNow)
        { 
            nextTick += CLOCKS_PER_SEC;
            printf("internal clock = %ld\n", timeNow);
        }
    }
    return 0;
}
commented Jun 28, 2023 by Alexander Urezchenko (190 points)
Thanks a lot!
0 votes
answered Jul 28, 2023 by Gulshan Negi (1,580 points)

Hello, this is Gulshan Negi

Well, there are some issue with print function, here is the correct code: 

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

int main()
{
    long int lastTime = time(NULL); // Get the current time in seconds since the epoch
    while (1) {
        if (lastTime < time(NULL) - 1) { // Compare the current time with lastTime + 1 second
            lastTime = time(NULL); // Update lastTime with the new current time
            printf("Internal time = %ld\n", lastTime);
        }
    }
    return 0;
}

Thanks

commented Jul 29, 2023 by Peter Minarik (89,230 points)
Your code does not print the time every second as the poster wanted to.
commented Jul 31, 2023 by Gulshan Negi (1,580 points)
Well, is it working find ?
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...