PythonMastery

Countdown timer and stopwatch in Python

A countdown timer that prints minutes and seconds with time.sleep(), and a stopwatch that measures elapsed time with time.perf_counter().

Two small tools from the time module: a countdown timer that waits one second between numbers, and a stopwatch that measures how long something took.

The program

python
import time


def countdown(seconds, tick=1.0):
    for remaining in range(seconds, 0, -1):
        minutes, secs = divmod(remaining, 60)
        print(f"{minutes:02}:{secs:02}")
        time.sleep(tick)
    print("Time's up!")


# tick=0.02 keeps this example fast; leave out tick for a real 1-second timer
countdown(5, tick=0.02)
output
00:05
00:04
00:03
00:02
00:01
Time's up!

How it works

A stopwatch

To measure time, read a clock before and after, and subtract. time.perf_counter() is the clock made for this: it is the most precise one, and it is not affected if the computer's clock is changed while your program runs.

python
import time

start = time.perf_counter()
time.sleep(0.1)  # stands in for the work you want to time
elapsed = time.perf_counter() - start
print(f"Elapsed: {elapsed:.1f} seconds")
example output · yours will differ
Elapsed: 0.1 seconds

The real elapsed time is a little more than 0.1 seconds, and it changes slightly every run. :.1f rounds it to one decimal place. For a stopwatch you control with the keyboard, read the clock after one input("Press Enter to start") and again after a second input("Press Enter to stop").

Learn the idea: Loops: for, while, and the Pythonic Patterns, Modules & Imports

A longer explanation: How do I measure how long my Python code takes to run?