Displaying time in human readable form

Posted by Jiro Doke,

Jiro's pick this week is seconds2human by Rody Oldenhuis.

There was a time when I obsessed over waitbars. Why is that? I'm not sure, but Ned has a few guesses. But one of the features that I look for in these waitbar entries is the ability to show the remaining time, like some of these. I have created my own waitbar as well to include the time remaining, and I remember thinking quite a bit about how I display the time. I can easily calculate the time using tic and toc. But what's the best way to display the seconds? It's probably better to say "3 hours 44 minutes 13 seconds remaining" than to say "13453 seconds remaining". So I had to do some manipulations to have an appropriate display, and many of the entries I highlighted above do that as well.

Rody's seconds2human does this nicely. You simply pass in the time in seconds, and it will convert it to something human understandable. There's an approximate display:

seconds2human(13453)

ans =
About 3 hours and 44 minutes.


and an accurate display:

seconds2human(13453,'full')

ans =
3 hours, 44 minutes, 13 seconds.


Now, I can just make use of this and not have to worry about decomposing the seconds.

hWait = waitbar(0, 'Calculating...');
total = 1000;
% Start timer
tstart = tic;
for iter = 1:total
SomeComputation(iter);
% Calculate remaining time
remaining = toc(tstart)*(total-iter)/iter;
% Update waitbar
waitbar(iter/total,hWait, ...
['Time remaining: ',seconds2human(remaining)])
end
delete(hWait);