-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_await.py
More file actions
54 lines (45 loc) · 1.59 KB
/
Copy pathasync_await.py
File metadata and controls
54 lines (45 loc) · 1.59 KB
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
# ============================================
# Python Concurrency Playground
# Demonstrates:
# 1. Async Programming (async/await)
# ============================================
# -----------------------
# Synchronous Approach
# -----------------------
import time
def write_sync():
"""A simple synchronous function that simulates work."""
print("Hey")
time.sleep(1) # Simulate a 1-second task
print("there")
def main_sync():
"""Calls write_sync() 10 times sequentially."""
for _ in range(10):
write_sync()
if __name__ == "__main__":
print("\n--- Running Synchronous Code ---")
start = time.perf_counter() # Start timing
main_sync()
elapsed = time.perf_counter() - start # End timing
print(f"Synchronous executed in {elapsed:0.2f} seconds\n")
# -----------------------
# Asynchronous Approach
# -----------------------
import asyncio
async def write_async():
"""A simple asynchronous function that simulates work."""
print("Hey")
await asyncio.sleep(1) # Simulate a 1-second async task
print("there")
async def main_async():
"""Runs write_async() 10 times concurrently."""
await asyncio.gather(
write_async(), write_async(), write_async(), write_async(), write_async(),
write_async(), write_async(), write_async(), write_async(), write_async()
)
if __name__ == "__main__":
print("--- Running Asynchronous Code ---")
start = time.perf_counter() # Start timing
asyncio.run(main_async())
elapsed = time.perf_counter() - start # End timing
print(f"Asynchronous executed in {elapsed:0.2f} seconds")