Quite often, I find myself measuring how long some part of my code takes to complete. I normally do that by storing current time using time.time()
and then subtracting time after the code is done.
This normally gives me a float that I can then format and print for debugging purposes. This is the function that I have for time formatting:
def time_format(delta: float) -> str:
output = []
decimal, integer = math.modf(delta)
if integer:
minutes, seconds = divmod(int(integer), 60)
if minutes:
output.append("%sm" % minutes)
if seconds:
output.append("%ss" % seconds)
decimal, integer = math.modf(decimal * 1000)
if integer:
output.append("%sms" % int(integer))
decimal, integer = math.modf(decimal * 1000)
if integer:
output.append("%sμs" % int(integer))
decimal, integer = math.modf(decimal * 1000)
if integer:
output.append("%sns" % int(integer))
return ", ".join(output)
I have also been told that the time module has most precision when it comes to time measuring so that's why I'm using it, instead of something like datetime which has nice formatting tools built in.
How could I improve my time formatting function? Are there any built in formatting tools that I'm not aware of? (Searching stack overflow leads me only to questions about datetime.timedelta)
timedelta(seconds=delta)
and work from there? \$\endgroup\$ – 301_Moved_Permanently Feb 26 '19 at 7:10