![]() |
VOOZH | about |
Task is to build a simple lap timer in Python that records and displays the time for each lap and the total elapsed time. The timer starts immediately, and each time the user presses the ENTER key, a new lap time is recorded. The timer continues running until the user stops it manually using CTRL+C.
Let’s explore different methods to create a lap timer in Python.
This method uses the "time.perf_counter()" function, which provides high-resolution timing and is more accurate for measuring small intervals. It continuously tracks time and prints lap and total durations every time the user presses ENTER.
Output
Press ENTER to record laps.
Press CTRL+C to stop
Lap No.: 1
Total Time: 1.9188
Lap Time: 1.9188
********************
Lap No.: 2
Total Time: 3.5742
Lap Time: 1.6555
********************
Lap No.: 3
Total Time: 4.1417
Lap Time: 0.5675
********************
Done
Explanation:
This method uses Python’s built-in time module to measure elapsed time between laps. The time.time() function returns the current time in seconds since the epoch. Each time the user presses ENTER, it calculates the lap time and total time by subtracting previous timestamps.
Output
Press ENTER to count laps.
Press CTRL+C to stop
Lap No. 1
Total Time: 3.05
Lap Time: 3.05
********************
Lap No. 2
Total Time: 4.33
Lap Time: 1.28
********************
Lap No. 3
Total Time: 5.26
Lap Time: 0.93
********************
Done
Explanation: