Edit 2: Cooldown:
The following code
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))
Edit: This might be what you want:
import time
for i in range(1,11):
print(i)
time.sleep(1)
This one counts up from 1 to 10. You can reverse it by
import time
for i in reversed(range(1,11)):
print(i)
time.sleep(1)
First answer below
This is one way you could do a basic timer in 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)
This now prints (approx) 10
because it took 10 seconds to run the above code.
You could also look at iPython
s %timeit!
Addendum
You could also make this even bigger, and make a Timer
class, like so:
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)
Now you can just run t=Timer()
followed by t.tick()
and t.tock()
to start and stop the timer respectively (multiple times(!)), and then print(t)
to see all the recorded times. E.g.
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)