I also wanted to note that the function fails if the process completes in less than 1 second, as @Dean O also pointed out. I've added:
if (is_null($duration))
$duration = array('less than 1 second');
before the return statement to handle this case.
IMO, this is a better alternative to what @Dean O suggests since it results in correct output under all use cases.