编辑 2: 冷却时间:
以下代码
import time
import random
# Minimum time (in seconds) that it has to wait
for i in range(10):
minimum_time=3
tick=time.time()
# How much time has passed since tick?
passed_time=time.time()-tick
# Sleep a random amount of time
time.sleep(random.uniform(0,3))
# Check if the passed time is less than the minimum time
if passed_time<minimum_time:
# If it is not passed enough time
# then sleep the remaining time
time.sleep(minimum_time-passed_time)
print("{} seconds were used in this iteration of the loop, and it should be _at least_ 3".format(time.time()-tick))
编辑:这可能是你想要的:
import time
for i in range(1,11):
print(i)
time.sleep(1)
这个从 1 数到 10。你可以把它倒过来
import time
for i in reversed(range(1,11)):
print(i)
time.sleep(1)
下面的第一个答案
这是你可以在 python 中做一个基本计时器的一种方法:
import time
# Get the current unix time stamp (that is time in seconds from 1970-01-01)
first=time.time()
# Sleep (pause the script) for 10 seconds
# (remove the line below and insert your code there instead)
time.sleep(10)
# Get the _now_ current time (also in seconds from 1970-01-01)
# and see how many seconds ago we did it last time
delta=time.time()-first
print(delta)
现在打印(大约)10,因为运行上述代码需要 10 秒。
你也可以看看iPythons %timeit!
附录
你也可以把它做得更大,创建一个 Timer 类,像这样:
import time
class Timer():
def __init__(self):
self.times=[]
self._tick=0
def tick(self):
""" Call this to start timer """
# Store the current time in _tick
self._tick=time.time()
def tock(self):
""" Call this to stop timer """
# Add the delta in the times-list
self.times.append(time.time()-self._tick)
def __str__(self):
# This method is just so that the timer can be printed nicely
# as further below
return str(self.times)
现在您可以运行t=Timer(),然后运行t.tick() 和t.tock() 来分别启动和停止计时器(多次(!)),然后运行print(t) 来查看所有记录的时间。例如
t=Timer()
for i in range(4):
t.tick()
# Sleep (pause the script) for 10 seconds
# (remove the line below and insert your code there instead)
time.sleep(1)
# Get the _now_ current time (also in seconds from 1970-01-01)
# and see how many seconds ago we did it last time
t.tock()
print(t)