Python Implement a Stopwatch
The following example uses the time module to implement a stopwatch:
Example
import
time
(
'
Press Enter to start timing; press Ctrl + C to stop.
'
)
while
True
:
input
(
"
"
)
Wait for the user to press Enter to start timing
start_time
=
time
.
time
(
)
Record the start time
(
'
Starting timing...
'
)
try
:
while
True
:
elapsed_time
=
round
(
time
.
time
(
)
start_time
,
0
)
Calculate the elapsed time
Key fix: flush=True forces real-time refresh + \r overwrites the beginning of the line
(
f
'
Timing: {elapsed_time} seconds
'
,
end
=
"
\r
"
,
flush
=
True
)
time
.
sleep
(
1
)
except
KeyboardInterrupt
:
Catch the Ctrl + C interrupt signal
end_time
=
time
.
time
(
)
Record the end time
total_time
=
round
(
end_time
start_time
,
2
)
(
f
'
\n
Timing finished, total time: {total_time} seconds
'
)
break
The test result is:
按下回车开始计时,按下 Ctrl + C 停止计时。
开始计时...
^C时: 3.0 秒
计时结束,总共时间为: 3.77 秒