Dưới đây là một giải pháp mà tôi bắt đầu sử dụng thời gian gần đây:
class Timer:
def __enter__(self):
self.begin = now()
def __exit__(self, type, value, traceback):
print(format_delta(self.begin, now()))
Bạn sử dụng nó như thế này (Bạn cần ít nhất Python 2.5):
with Timer():
do_long_code()
Khi mã của bạn kết thúc, hẹn giờ tự động in ra thời gian chạy. Ngọt! Nếu tôi đang cố gắng sắp xếp một cách nhanh chóng thứ gì đó trong Python Interpreter, đây là cách dễ nhất để đi.
Và đây là triển khai mẫu 'hiện tại' và 'format_delta', mặc dù bạn có thể thoải mái sử dụng phương pháp định dạng và thời gian ưa thích của mình.
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
Vui lòng cho tôi biết nếu bạn có phương pháp định dạng ưa thích hoặc nếu có cách dễ dàng hơn để thực hiện tất cả điều này!
liên quan: [Đo thời gian trôi qua bằng Python?] (Http://stackoverflow.com/q/7370801/4279) – jfs