Python Stopwatch Implementation

The following example uses the time module to implement a stopwatch:

Example

import time print('Press Enter to start timing, press Ctrl + C to stop timing.') while True: input("") # Wait for the user to press Enter to start timing start_time = time.time() # Record the start time print('Start 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 at the beginning of the line print(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) print(f'\nTiming ended, total time: {total_time} seconds') break

The test result is:

按下回车开始计时,按下 Ctrl + C 停止计时。

开始计时...
^C时: 3.0 秒
计时结束,总共时间为: 3.77 秒
Other extensions