0

I was wondering how to track the current time in C to as much accuracy as possible. In particular, I was wondering if there was a function in C that mimics Python's time.time()?

I found the code below, but it rounds the seconds.

#include <time.h>
int main() {
  time_t seconds;
  seconds = time(NULL);
}

3 Answers3

2

If you use POSIX-compatible system you may try clock_gettime function. It returns the current time in nanoseconds.

#include <time.h>
#include <stdint.h>
int main() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    int64_t time_ns = ts.tv_sec * 1000000000LL + ts.tv_nsec;
    return 0;
}
Oleg Utkin
  • 171
  • 1
  • 3
  • 2
    `ts.tv_sec * 1000000000` can reallily overflow a [32-bit `time_t`](https://en.wikipedia.org/wiki/Year_2038_problem). Suggest `ts.tv_sec * 1000000000LL` or the like to insure at least a 64-bit multiplication. – chux - Reinstate Monica Jun 17 '20 at 19:02
0

This should help:

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

int main()
{
    clock_t t1, t2;
    t1 = clock();
    float diff = (t1 / 1000000.0F );
    printf("%f",diff);

    return 0;
}
Deepthought
  • 118
  • 9
0

You can use the clock function from time.h to measure time with extreme precision.

It'll return the number of clocks elapsed since a reference frame (which is implementation defined but it's related to the program's execution).

#include <time.h>
clock_t now = clock();

Now if you want to turn this into an actually understandable time unit, you should divide the result of clock() by CLOCKS_PER_SEC, maybe even multiply it by 1000 to get the result in milliseconds (the precision should be preserved after dividing by CLOCKS_PER_SEC)

double secs = now / CLOCKS_PER_SEC; // Result in seconds
double msecs = secs * 1000; // Result in milliseconds

This will work on all systems.

More information on clock

Chase
  • 5,315
  • 2
  • 15
  • 41
  • You need a cast `double secs = (double)now / CLOCKS_PER_SEC;` and also, on some systems you don't get millisecond resolution from `clock()`. – Weather Vane Jun 17 '20 at 18:11
  • @WeatherVane In practice, `(double)now` is OK, yet that could narrow the precision of `clock_t`. A more gentle alternative is `double secs = 1.0 * now / CLOCKS_PER_SEC;` to allow the division to occurs at best precision. – chux - Reinstate Monica Jun 17 '20 at 18:46
  • @chux-Reinstate Monica or `double secs = now / (double)CLOCKS_PER_SEC;` similar to another answer. Though `clock_t`'s precision isn't that great. – Weather Vane Jun 17 '20 at 18:48
  • @WeatherVane True in general. Yet `clock_t` and `time_t` are only specified as some scalar. It is just that casts can not only widen a type, sometimes they will narrow, so I try to avoid them unless no other good solution exists. IAC, your point about the weakness of `now / CLOCKS_PER_SEC;` remains valid. – chux - Reinstate Monica Jun 17 '20 at 18:59