C - Tips'n Tricks - Creating a clock with six numbers after the decimal point

Everyone knows that a clock is essential in a video game.

And the more the clock is precise, the more we can do things.

That's what we are going to see in this clock tutorial by creating a clock with six numbers after the decimal point.

The code

/* BadproG.com */

#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>

int clockTime();

int main(void)
{
    if (clockTime())
        return (1);
    return EXIT_SUCCESS;
}

/**
 * A clock with six numbers after the decimal point
 */
int clockTime()
{
    time_t t;
    struct timeval tv;
    double gtod;
    double theTime;

    theTime = 0;
    gtod = 0;
    t = time(NULL);
    while (t < 2000000000)
    {
        t = time(NULL);
        gtod = gettimeofday(&tv, NULL);
        if (gtod != 0)
        {
            fprintf(stderr, "Error: clockTime().\n");
            return (1);
        }
        theTime = (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
        printf("theTime = %f\n", theTime);
    }
    return (0);
}

The result

...
theTime = 1341489768.809641
theTime = 1341489768.809655
theTime = 1341489768.809670
theTime = 1341489768.809684
theTime = 1341489768.809698
theTime = 1341489768.809712
theTime = 1341489768.809726
theTime = 1341489768.809740
theTime = 1341489768.809755
theTime = 1341489768.809769
theTime = 1341489768.809783
theTime = 1341489768.809798
theTime = 1341489768.809812
theTime = 1341489768.809826
theTime = 1341489768.809840
theTime = 1341489768.809855
theTime = 1341489768.809869
theTime = 1341489768.809884
...

You can now check an action more quickly than before.
You made it, well done. wink

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.