Python time.sleep 函数
上次修改时间:2025 年 4 月 11 日
这份全面的指南探讨了 Python 的 time.sleep
函数,该函数会暂停执行指定的秒数。我们将涵盖基本用法、时间控制和实际示例。
基本定义
time.sleep
函数会暂停当前线程的执行,持续指定的秒数。该参数可以是浮点数,以实现亚秒级精度。
主要特点:平台相关的精度(通常优于毫秒),非忙等待(释放 CPU)以及可通过 KeyboardInterrupt(Ctrl+C)中断。
基本 Sleep 示例
time.sleep
的最简单用法是暂停程序执行。此示例显示了不同延迟持续时间的基本用法。
import time print("Starting...") time.sleep(1) # Sleep for 1 second print("1 second has passed") time.sleep(0.5) # Sleep for 500 milliseconds print("500 milliseconds have passed") time.sleep(0.001) # Sleep for 1 millisecond print("1 millisecond has passed")
此示例演示了如何暂停执行不同的持续时间。睡眠持续时间可以指定为整数或浮点数。
请注意,由于系统调度和其他因素,实际睡眠持续时间可能会略有差异。
创建倒计时器
time.sleep
可用于创建简单的计时器。此示例显示了一个倒计时器,该计时器会打印剩余秒数。
import time def countdown(seconds): while seconds > 0: print(f"Time remaining: {seconds} seconds") time.sleep(1) seconds -= 1 print("Time's up!") countdown(5)
这种模式对于简单的计时操作很有用。循环在每个睡眠间隔后递减计数器。
为了更精确的计时,请考虑使用 time.perf_counter
来考虑睡眠的不准确性。
使用 Sleep 进行速率限制
此示例使用 time.sleep
来实现 API 调用或其他需要限制的操作的速率限制。
import time def make_api_call(): print("Making API call at", time.strftime("%H:%M:%S")) def rate_limited_call(calls_per_minute): interval = 60 / calls_per_minute while True: make_api_call() time.sleep(interval) # Limit to 10 calls per minute rate_limited_call(10)
睡眠持续时间基于所需的调用速率计算。这确保了调用在时间上均匀分布。
对于生产用途,请考虑添加错误处理和退出条件。
创建简单动画
time.sleep
可以通过控制帧之间的时间来创建简单的文本动画。此示例显示了一个旋转的轮子动画。
import time def spinning_wheel(duration): frames = ['-', '\\', '|', '/'] end_time = time.time() + duration while time.time() < end_time: for frame in frames: print(f"\rLoading {frame}", end="", flush=True) time.sleep(0.1) print("\nDone!") spinning_wheel(5) # Run for 5 seconds
该动画通过以每个动画之间的小延迟循环播放帧来工作。 \r
将光标移动到行首以进行覆盖。
此技术可以适用于进度条或其他简单动画。
模拟处理时间
在开发过程中,time.sleep
通常用于模拟处理时间。此示例显示了一个模拟文件处理函数。
import time import random def process_file(filename): print(f"Starting processing of {filename}") # Simulate variable processing time processing_time = random.uniform(0.5, 2.5) time.sleep(processing_time) print(f"Finished processing {filename} in {processing_time:.2f} seconds") return True files = ["data1.txt", "data2.txt", "data3.txt"] for file in files: process_file(file)
随机睡眠持续时间模拟可变的处理时间。这对于测试处理异步操作的系统很有用。
在实际应用中,将睡眠替换为实际的处理代码。
创建轮询机制
此示例使用 time.sleep
来实现一个轮询循环,该循环以固定的时间间隔检查一个条件。
import time def wait_for_condition(condition_func, timeout=30, interval=1): """ Wait for condition_func to return True or timeout. """ start_time = time.time() while time.time() - start_time < timeout: if condition_func(): return True time.sleep(interval) return False # Example usage: def check_file_exists(): # In real code, this would check filesystem return time.time() > start_time + 3 # Simulate file appearing after 3 seconds start_time = time.time() result = wait_for_condition(check_file_exists) print(f"Condition met: {result}")
轮询循环以固定的时间间隔检查条件,同时在检查之间休眠。 这可以防止消耗 CPU 资源的忙等待。
对于生产用途,请考虑向间隔添加抖动以避免惊群问题。
最佳实践
- 精度: 不保证睡眠持续时间完全准确
- 替代方案: 对于精确计时,请考虑基于事件的方法
- 中断: 可以使用 KeyboardInterrupt 中断睡眠
- 线程: 仅暂停当前线程
- GUI 应用程序: 避免在 GUI 应用程序的主线程中使用睡眠
资料来源
作者
列出所有 Python 教程。