1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
| """ 第1课示例代码:同步 vs 异步对比
运行方式: python 01_examples.py """
import asyncio import time from typing import List
def cook_coffee_sync() -> None: """同步方式:煮咖啡""" print("☕ 开始煮咖啡...") time.sleep(5) print("☕ 咖啡煮好了!")
def toast_bread_sync() -> None: """同步方式:烤面包""" print("🍞 开始烤面包...") time.sleep(3) print("🍞 面包烤好了!")
def fry_eggs_sync() -> None: """同步方式:煎鸡蛋""" print("🍳 开始煎鸡蛋...") time.sleep(4) print("🍳 鸡蛋煎好了!")
def make_breakfast_sync() -> None: """同步方式做早餐:一件一件做""" print("\n" + "=" * 50) print("🏃 方式一:同步方式做早餐(一件一件做)") print("=" * 50)
start_time = time.time()
cook_coffee_sync() toast_bread_sync() fry_eggs_sync()
end_time = time.time() total_time = end_time - start_time
print(f"\n✅ 早餐做好了!total_time:{total_time:.1f}秒") print("💭 分析:我们大部分时间都在等待,效率很低...")
async def cook_coffee_async() -> None: """异步方式:煮咖啡""" print("☕ 开始煮咖啡...") await asyncio.sleep(5) print("☕ 咖啡煮好了!")
async def toast_bread_async() -> None: """异步方式:烤面包""" print("🍞 开始烤面包...") await asyncio.sleep(3) print("🍞 面包烤好了!")
async def fry_eggs_async() -> None: """异步方式:煎鸡蛋""" print("🍳 开始煎鸡蛋...") await asyncio.sleep(4) print("🍳 鸡蛋煎好了!")
async def make_breakfast_async() -> None: """异步方式做早餐:同时做多件事""" print("\n" + "=" * 50) print("🚀 方式二:异步方式做早餐(同时做多件事)") print("=" * 50)
start_time = time.time()
await asyncio.gather( cook_coffee_async(), toast_bread_async(), fry_eggs_async() )
end_time = time.time() total_time = end_time - start_time
print(f"\n✅ 早餐做好了!total_time:{total_time:.1f}秒") print("💭 分析:在等待的时间里做其他事情,效率大大提高!")
def download_file_sync(filename: str, duration: int) -> None: """同步方式:download_file""" print(f"📥 开始下载 {filename}...") time.sleep(duration) print(f"✅ {filename} 下载完成!")
def batch_download_sync() -> None: """同步方式:批量下载文件""" print("\n" + "=" * 50) print("🏃 同步方式:批量下载5个文件") print("=" * 50)
start_time = time.time()
download_file_sync("文件1.pdf", 2) download_file_sync("文件2.jpg", 3) download_file_sync("文件3.mp4", 4) download_file_sync("文件4.zip", 2) download_file_sync("文件5.doc", 3)
end_time = time.time() total_time = end_time - start_time
print(f"\n✅ 全部下载完成!total_time:{total_time:.1f}秒")
async def download_file_async(filename: str, duration: int) -> None: """异步方式:download_file""" print(f"📥 开始下载 {filename}...") await asyncio.sleep(duration) print(f"✅ {filename} 下载完成!")
async def batch_download_async() -> None: """异步方式:批量下载文件""" print("\n" + "=" * 50) print("🚀 异步方式:批量下载5个文件") print("=" * 50)
start_time = time.time()
await asyncio.gather( download_file_async("文件1.pdf", 2), download_file_async("文件2.jpg", 3), download_file_async("文件3.mp4", 4), download_file_async("文件4.zip", 2), download_file_async("文件5.doc", 3) )
end_time = time.time() total_time = end_time - start_time
print(f"\n✅ 全部下载完成!total_time:{total_time:.1f}秒") print(f"💡 效率提升:{14/total_time:.1f}倍!")
def performance_comparison_summary() -> None: """展示性能对比总结""" print("\n" + "=" * 50) print("📊 性能对比总结") print("=" * 50) print(""" 场景1:做早餐 同步方式:12秒(5+3+4) 异步方式:5秒(最长的任务) 效率提升:2.4倍 ⚡ 场景2:下载5个文件 同步方式:14秒(2+3+4+2+3) 异步方式:4秒(最长的任务) 效率提升:3.5倍 ⚡ 💡 结论: 当任务涉及"等待"(网络、file、数据库)时, 异步编程可以大幅提升效率! 等待的任务越多,提升越明显! """)
async def main() -> None: """主程序:运行所有示例""" print("🎓 第1课:什么是异步编程?") print("=" * 50)
make_breakfast_sync() await make_breakfast_async()
batch_download_sync() await batch_download_async()
performance_comparison_summary()
print("\n" + "=" * 50) print("🎉 第1课完成!") print("=" * 50) print(""" 📚 你学到了什么? 1. 同步 = 排队做事(一个接一个) 2. 异步 = 同时做事(充分利用等待时间) 3. 异步在I/O密集型任务中效率极高 🎯 下一步: 学习 async/await 语法(第2课) 💪 动手练习: 1. 修改上面的等待时间,观察效果变化 2. 增加更多任务,看看效率提升有多大 3. 思考你的工作中哪些场景可以用异步 """)
if __name__ == "__main__": asyncio.run(main())
|