Python Program to Create a Stopwatch
time module by recording the start time with time.time(), then calculating elapsed time by subtracting the start time from the current time.Examples
How to Think About It
Algorithm
Code
import time print('Press Enter to start the stopwatch') input() start_time = time.time() print('Stopwatch started... Press Enter to stop') input() end_time = time.time() elapsed_time = end_time - start_time print(f'Elapsed time: {elapsed_time:.2f} seconds')
Dry Run
Let's trace starting the stopwatch, waiting 2 seconds, then stopping it.
User presses Enter to start
start_time = 1700000000.00 (example timestamp)
User waits 2 seconds
Time passes...
User presses Enter to stop
end_time = 1700000002.00 (example timestamp)
Calculate elapsed time
elapsed_time = 1700000002.00 - 1700000000.00 = 2.00 seconds
Display elapsed time
Print 'Elapsed time: 2.00 seconds'
| Step | Action | Value |
|---|---|---|
| 1 | Start time recorded | 1700000000.00 |
| 2 | Wait | 2 seconds |
| 3 | End time recorded | 1700000002.00 |
| 4 | Elapsed time calculated | 2.00 seconds |
| 5 | Output elapsed time | Elapsed time: 2.00 seconds |
Why This Works
Step 1: Record start time
Using time.time() captures the current time in seconds since a fixed point, so we know when the stopwatch started.
Step 2: Record end time
When stopping, calling time.time() again gives the current time to compare with the start.
Step 3: Calculate elapsed time
Subtracting start time from end time gives the total seconds passed, which is the stopwatch duration.
Step 4: Display result
Printing the elapsed time with formatting shows the user how long the stopwatch ran.
Alternative Approaches
import time input('Press Enter to start') start = time.perf_counter() input('Press Enter to stop') end = time.perf_counter() print(f'Elapsed time: {end - start:.2f} seconds')
import time class Stopwatch: def __init__(self): self.start_time = None def start(self): self.start_time = time.time() def stop(self): return time.time() - self.start_time sw = Stopwatch() input('Press Enter to start') sw.start() input('Press Enter to stop') elapsed = sw.stop() print(f'Elapsed time: {elapsed:.2f} seconds')
Complexity: O(1) time, O(1) space
Time Complexity
The stopwatch program runs in constant time because it only records timestamps and calculates their difference once.
Space Complexity
It uses a fixed amount of memory to store start and end times, so space complexity is constant.
Which Approach is Fastest?
Using time.perf_counter() is slightly faster and more precise than time.time(), but both are efficient for this use.
| Approach | Time | Space | Best For |
|---|---|---|---|
| time.time() | O(1) | O(1) | Simple stopwatch with wall-clock time |
| time.perf_counter() | O(1) | O(1) | High precision timing |
| Class-based stopwatch | O(1) | O(1) | Reusable and extendable stopwatch code |
time.perf_counter() for more accurate timing in stopwatches.