Time Difference

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.

Pocket Watch

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,

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?
Continue reading