0

I need to find the difference of 2 time stamps having format YYYY DD MM HH MM SS MSC. For example, the difference of 2022 08 13 08 17 20 512 and 2022 08 13 08 17 20 000 should return 512 msec.

I have gone through the posts in How to convert from UTC to local time in C?.

mktime using struct tm pointer has a provision to represent till seconds resolution. Which function should we use to include milliseconds portion as well for computation?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Soumajit
  • 342
  • 2
  • 4
  • 16
  • `2 time stamps having format` In what timezone are the timestamps? `has provision to represent till seconds resolution.` soooo handle seconds and milliseconds yourself? I do not understand. `Which function should we use to include milliseconds portion as well for computation ?` Write one yourself? After `mktime` it's just `seconds * 1000 + milliseconds`. `How to get the difference of time stamps having milliseconds portion using C in Linux?` Represent the time in milliseconds. Subtract. – KamilCuk Aug 13 '22 at 13:00
  • @KamilCuk the timestamps are in UTC time zone. I was thinking if any system function is already available, i can use them. – Soumajit Aug 13 '22 at 13:10
  • `are in UTC time zone` So remember to set timezone before calling `mktime`. `I was thinking if any system function is already available` There is none. With glibc there is `timersub` for `struct timeval`. There's also better `struct timespec`, but no functions I know of. – KamilCuk Aug 13 '22 at 14:00
  • For Linux (especially if you're writing normal software and can't reconfigure the OS or kernel to suit yourself); you can expect that all your hopes and dreams will be destroyed as soon as you expect anything to work properly for leap seconds. – Brendan Aug 14 '22 at 07:05

1 Answers1

0

C provides difftime to figure out the number of seconds and timegm is helpful for the UTC timezone. Watch out for that tricky tm_mon element (number of months since January, so August is really 7 not 8).

Maybe extend on the result from difftime by adding the msec difference?

Something like this?

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

struct TIME {
  struct tm tm;
  unsigned int tm_msec;
};

double difftime_ms( struct TIME *time2, struct TIME *time1 )
{
  time_t t1 = timegm( &time1->tm );
  time_t t2 = timegm( &time2->tm );
  return ( 1000.0 * difftime( t2, t1 ) + ( time2->tm_msec - time1->tm_msec ) );
}

int main()
{
  struct TIME time1 = { .tm = { .tm_year = 2022, .tm_mon = (8-1), .tm_mday = 13, .tm_hour = 8, .tm_min = 17, .tm_sec = 20} , .tm_msec = 000 };
  struct TIME time2 = { .tm = { .tm_year = 2022, .tm_mon = (8-1), .tm_mday = 13, .tm_hour = 8, .tm_min = 17, .tm_sec = 20} , .tm_msec = 512 };

  printf( "Difference is %.2f msec\n", difftime_ms( &time2, &time1 ) );
  return 0;
}

atl
  • 575
  • 3
  • 6