user18769752
user18769752

Reputation:

Taking the difference between two changing times

I want to subtract two times from each other that are of the format MM DD YYYY HH:MM:SS.ns.

This is a code snippet of what is pasted at the top and bottom of my program since I am taking the overall time of a program for individual calculations:

clock_gettime(CLOCK_REALTIME, &start);
struct tm* start_timer = localtime(&start.tv_sec);
size_t ns1 = strftime(timer, 100, "%B %e, %G %R:%S.", start_timer);

snprintf(timer + ns1, 100 - ns1, "%.9ld", start.tv_nsec);
fprintf(fout, "%s", timer);

/*---------------------------------
 Main function doing calculations
-----------------------------------*/

clock_gettime(CLOCK_REALTIME, &end);
struct tm* stop_timer = localtime(&end.tv_sec);
size_t ns2 = strftime(timer, 100, "%B %e, %G %R:%S.", stop_timer);

snprintf(timer + ns2, 100 - ns2, "%.9ld", end.tv_nsec);
fprintf(fout, "%s", timer);

Once the calculations are done, the start time and end times are printed (just as an example):

Start time: April 12, 2022 13:45:29.123456789
End time: April 12, 2022 13:45:51.234567890

Basically, these values are constantly changing based on when I run, and how long the program runs. What I want to do is take the difference between these times to report an overall time for the entire program. By this I mean I want it to print like this:

Overall time: 03:12.345678901

How do I achieve this? I was thinking that I would have to use strptime for this, and I know that difftime will be a player, but I'm not entirely sure about how I'd do that since the variables are constantly changing. I would assume to store these into variables, but I get an error saying this:

assignment to ‘time_t’ {aka ‘long int’} from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]

Upvotes: 1

Views: 82

Answers (1)

chux
chux

Reputation: 154582

To find time between start and end subtract both members.

double diff_seconds = difftime(end.tv_sec, start.tv_sec) + 
    (end.tv_nsec - start.tv_nsec)/1.0e9;

I want it to print like this: "Overall time: 03:12.345678901"

double min = trunc(diff_seconds / 60);
double sec = diff_seconds - min * 60;
// Possible format - needs checking
printf("Overall time: %02.0f:%02.9f\n", min, sec);

Due to rounding, I am wondering if "xxxx.60.000000000" is possible - hmmm....

That is possible when diff_seconds is more than say, 17 years, so for OP, not a big concern.

Alternative code could insure diff_seconds * 10e9 fits in a long long and then process the nano_seconds as a large integer - not shown.

Upvotes: 2

Related Questions