import time
start_time=time.time() #taking current time as starting time
#here your code
elapsed_time=time.time()-start_time #again taking current time - starting time
import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
将打印出来,持续2秒:
'00:00:02'
在7分1秒内:
'00:07:01'
注意,gmtime的最小时间单位是秒。如果您需要微秒,请考虑以下内容:
import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds)
与结构会自动调用< em > __enter__ < / em >和< em > __exit__ < / em >方法,这正是我们为事情计时所需要的。
让我们创建一个计时器类。
from time import time
class Timer():
def __init__(self, message):
self.message = message
def __enter__(self):
self.start = time()
return None # could return anything, to be used like this: with Timer("Message") as value:
def __exit__(self, type, value, traceback):
elapsed_time = (time() - self.start) * 1000
print(self.message.format(elapsed_time))
然后,你可以像这样使用Timer类:
with Timer("Elapsed time to compute some prime numbers: {}ms"):
primes = []
for x in range(2, 500):
if not any(x % p == 0 for p in primes):
primes.append(x)
print("Primes: {}".format(primes))
>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001 # took 0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075 # took 10 seconds and a bit