Aquí es una solución que he empezado a utilizar recientemente:
class Timer:
def __enter__(self):
self.begin = now()
def __exit__(self, type, value, traceback):
print(format_delta(self.begin, now()))
Se utiliza como esto (Se necesita al menos Python 2.5):
with Timer():
do_long_code()
Cuando el código termine, temporizador imprime automáticamente el tiempo de ejecución. ¡Dulce! Si estoy tratando de ubicar algo rápidamente en el intérprete de Python, esta es la forma más fácil de hacerlo.
Y aquí hay una implementación de ejemplo de 'now' y 'format_delta', aunque puede usar su método preferido de tiempo y formato.
import datetime
def now():
return datetime.datetime.now()
# Prints one of the following formats*:
# 1.58 days
# 2.98 hours
# 9.28 minutes # Not actually added yet, oops.
# 5.60 seconds
# 790 milliseconds
# *Except I prefer abbreviated formats, so I print d,h,m,s, or ms.
def format_delta(start,end):
# Time in microseconds
one_day = 86400000000
one_hour = 3600000000
one_second = 1000000
one_millisecond = 1000
delta = end - start
build_time_us = delta.microseconds + delta.seconds * one_second + delta.days * one_day
days = 0
while build_time_us > one_day:
build_time_us -= one_day
days += 1
if days > 0:
time_str = "%.2fd" % (days + build_time_us/float(one_day))
else:
hours = 0
while build_time_us > one_hour:
build_time_us -= one_hour
hours += 1
if hours > 0:
time_str = "%.2fh" % (hours + build_time_us/float(one_hour))
else:
seconds = 0
while build_time_us > one_second:
build_time_us -= one_second
seconds += 1
if seconds > 0:
time_str = "%.2fs" % (seconds + build_time_us/float(one_second))
else:
ms = 0
while build_time_us > one_millisecond:
build_time_us -= one_millisecond
ms += 1
time_str = "%.2fms" % (ms + build_time_us/float(one_millisecond))
return time_str
Por favor, hágamelo saber si usted tiene un método preferido de formato, o si hay una manera más fácil de hacer todo esto!
relacionado: [¿Mide el tiempo transcurrido en Python?] (Http://stackoverflow.com/q/7370801/4279) – jfs