Python带毫秒倒计时器实现问题:如何在现有秒级倒计时代码中提取毫秒
Great question! The issue with your current code is that it relies on time.sleep(1) and decrements the timer by 1 full second each iteration—so it can't track or display milliseconds. To fix this, we need to switch to tracking the actual elapsed time using precise timestamps, then calculate the remaining time including milliseconds on each loop iteration.
Here's a modified version of your countdown function that supports millisecond display:
import time def countdown(t): start_time = time.time() end_time = start_time + t # Calculate the exact moment the countdown ends while time.time() < end_time: remaining_time = end_time - time.time() # Break down remaining time into minutes, seconds, and milliseconds minutes = int(remaining_time // 60) seconds = int(remaining_time % 60) milliseconds = int((remaining_time - int(remaining_time)) * 1000) # Format the timer string with leading zeros and millisecond precision timer_display = '{:02d}:{:02d}.{:03d}'.format(minutes, seconds, milliseconds) # Overwrite the current line with the updated timer print(timer_display, end="\r") # Sleep for 1ms to keep updates smooth without excessive CPU usage time.sleep(0.001) print('Fire in the hole!!') # Accept input (supports decimals for millisecond precision, e.g., 5.5 = 5s 500ms) t = float(input("Enter the time in seconds (can include decimals for milliseconds): ")) countdown(t)
Key Changes Explained:
- Timestamp-Based Tracking: Instead of decrementing a counter, we calculate the exact end time by adding your input duration to the start time.
time.time()returns the current time in seconds (including fractional values for milliseconds/microseconds), so this gives us precise timing. - Millisecond Extraction: The fractional part of
remaining_time(the digits after the decimal point) represents sub-second time. Multiplying this by 1000 converts it to milliseconds, which we format as a 3-digit number for consistency. - Accurate Updates: Using
time.sleep(0.001)ensures the display refreshes every millisecond for smooth visual feedback, while avoiding unnecessary CPU load. - Flexible Input: The function now accepts float values (like
3.141for 3 seconds and 141 milliseconds) instead of just integers, giving you full control over millisecond precision.
Why This Is More Reliable:
Your original code could drift slightly over time because time.sleep(1) doesn't wait exactly 1 second (the loop's other operations add tiny overhead). This timestamp-based approach stays accurate by always comparing the current time to the fixed end time, so it never loses sync.
内容的提问来源于stack exchange,提问作者kakashi senpai

