This post is based on a discussion about Progress Bars of Life, where I was foolish enough to claim that printing a text string representing the difference between two times could not be that hard in C. It is not hard, but turned out not to be entirely trivial either.
The problem we will consider is; given two
tm structs, compute the difference in time between them, in such a way that we can easily format a string that gives a textual representation of it. We want years, months, days, hours, minutes, seconds.
The first idea you might get is to use
difftime() to get the difference in seconds between the two times, and then compute the quantities we want by simple arithmetic. So,
start_time = mktime(&start); end_time = mktime(&end); secdiff = difftime(end_time, start_time); years = secdiff / SEC_IN_YEAR; months = (secdiff % SEC_IN_YEAR) / SEC_IN_MONTH; days = (secdiff % SEC_IN_MONTH) / SEC_IN_DAY; hours = (secdiff % SEC_IN_DAY) / SEC_IN_HOUR; minutes = (secdiff % SEC_IN_HOUR) / SEC_IN_MINUTE; seconds = (secdiff % SEC_IN_MINUTE);
You often see something like this in timing code — it works great for showing elapsed time in seconds, minutes, even hours. Do you see any problems with this approach?