Python Program to Create a Lap Timer
In this article, we will make a simple timer to calculate lap-time intervals using Python.
time: This module provides various time-related functions. It is a part of Python’s standard library and does not require installation.
Approach:
The user needs to press ENTER to complete each lap. The timer keeps counting till CTRL+C is pressed. For each lap we calculate the lap time by subtracting the current time from the total time at the end of the previous lap. The time() function of the time module, returns the current epoch time in milliseconds.
Below is the implementation:
Python3
import time
starttime = time.time()
lasttime = starttime
lapnum = 1
print ( "Press ENTER to count laps.\nPress CTRL+C to stop" )
try :
while True :
input ()
laptime = round ((time.time() - lasttime), 2 )
totaltime = round ((time.time() - starttime), 2 )
print ( "Lap No. " + str (lapnum))
print ( "Total Time: " + str (totaltime))
print ( "Lap Time: " + str (laptime))
print ( "*" * 20 )
lasttime = time.time()
lapnum + = 1
except KeyboardInterrupt:
print ( "Done" )
|
Output:
ENTER to count laps.
Press CTRL+C to stop
Lap No. 1
Total Time: 1.09
Lap Time: 1.09
********************
Lap No. 2
Total Time: 2.66
Lap Time: 1.41
********************
Lap No. 3
Total Time: 5.06
Lap Time: 2.23
********************
Lap No. 4
Total Time: 5.63
Lap Time: 0.4
********************
Done
Time complexity: O(1) – the program runs in constant time, regardless of the size of the input.
Auxiliary space: O(1) – the program uses a fixed amount of memory, regardless of the size of the input
Last Updated :
28 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...