def human_time(timespan, precision=3):
    """Formats the timespan in a human readable format"""

    if timespan >= 60.0:
        # Format time greater than one minute in a human-readable format
        # Idea from http://snipplr.com/view/5713/
        def _format_long_time(time):
            suffixes = ('d', 'h', 'm', 's')
            lengths = (24*60*60, 60*60, 60, 1)

            for suffix, length in zip(suffixes, lengths):
                value = int(time / length)

                if value > 0:
                    time %= length
                    yield '%i%s' % (value, suffix)

                if time < 1:
                    break

        return ' '.join(_format_long_time(timespan))

    else:
        units = ['s', 'ms', 'us', 'ns']

        # Attempt to replace 'us' with 'µs' if UTF-8 encoding has been set
        if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding == 'UTF-8':
            try:
                units[2] = b'\xc2\xb5s'.decode('utf-8')
            except UnicodeEncodeError:
                pass

        scale = [1.0, 1e3, 1e6, 1e9]

        if timespan > 0.0:
            # Determine scale of timespan (s = 0, ms = 1, µs = 2, ns = 3)
            order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
        else:
            order = 3

        return '%.*g %s' % (precision, timespan * scale[order], units[order])
Formats the timespan in a human readable format