Skip to content

Commit 1a85c05

Browse files
6 - Async Functions in Python
1 parent 6589fc8 commit 1a85c05

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

index.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import time
2+
import asyncio # Python 3.5 +
3+
4+
iteration_times = [1, 3, 2, 4]
5+
start = time.time()
6+
total_time = 0
7+
real_time = 0
8+
async def sleeper(iteration, seconds): # coroutine
9+
global total_time
10+
global real_time
11+
func_start = time.time()
12+
print(f"{iteration}: {seconds}s")
13+
await asyncio.sleep(seconds)
14+
func_end = time.time() - func_start
15+
total_time += func_end
16+
real_time = func_end
17+
18+
async def run():
19+
results = []
20+
for iteration, second in enumerate(iteration_times):
21+
results.append(
22+
asyncio.create_task(
23+
sleeper(iteration, second)
24+
)
25+
)
26+
await asyncio.gather(*results)
27+
28+
asyncio.run(run())
29+
print(f"Took {total_time} seconds in compute time")
30+
print(f"Tooke {real_time} seconds in real time")
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import time
2+
import asyncio # Python 3.5 +
3+
4+
iteration_times = [1, 3, 2, 4]
5+
start = time.time()
6+
total_time = 0
7+
real_time = 0
8+
async def sleeper(iteration, seconds): # coroutine
9+
global total_time
10+
global real_time
11+
func_start = time.time()
12+
print(f"{iteration}: {seconds}s")
13+
await asyncio.sleep(seconds)
14+
func_end = time.time() - func_start
15+
total_time += func_end
16+
real_time = func_end
17+
18+
async def run():
19+
results = []
20+
for iteration, second in enumerate(iteration_times):
21+
results.append(
22+
asyncio.create_task(
23+
sleeper(iteration, second)
24+
)
25+
)
26+
await asyncio.gather(*results)
27+
28+
asyncio.run(run())
29+
print(f"Took {total_time} seconds in compute time")
30+
print(f"Tooke {real_time} seconds in real time")

reference_examples/py/sync_sleeper.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import time
2+
3+
iteration_times = [1, 3, 2, 4]
4+
start = time.time()
5+
total_time = 0
6+
def sleeper(iteration, seconds):
7+
global total_time
8+
func_start = time.time()
9+
print(f"{iteration}: {seconds}s")
10+
time.sleep(seconds)
11+
func_end = time.time() - func_start
12+
total_time += func_end
13+
14+
def run():
15+
for iteration, second in enumerate(iteration_times):
16+
sleeper(iteration, second)
17+
18+
run()
19+
print(f"Took {total_time} seconds")

0 commit comments

Comments
 (0)