-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathasyncio_ratelimit.py
More file actions
40 lines (26 loc) · 1.05 KB
/
asyncio_ratelimit.py
File metadata and controls
40 lines (26 loc) · 1.05 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
# ruff: noqa: T201
import asyncio
import logging
import time
from datetime import datetime
from pyrate_limiter import Limiter
from pyrate_limiter.limiter_factory import create_inmemory_limiter
logging.basicConfig(level=logging.DEBUG)
async def ticker():
for _ in range(10):
print(f"[TICK] {datetime.now()}")
await asyncio.sleep(0.5)
def mapping(name, weight, i):
return "mytask", 1
async def test_asyncio_ratelimit():
print("Running task_async using try_acquire_async and BucketAsyncWrapper")
print("Note that the TICKs continue while the tasks are waiting")
start = time.time()
limiter = create_inmemory_limiter()
async def task_async(name, weight, i, limiter: Limiter):
await limiter.try_acquire_async(name, weight)
print(f"try_acquire_async: {datetime.now()} {name}: {weight}")
await asyncio.gather(ticker(), *[task_async(str(i), 1, i, limiter) for i in range(10)])
print(f"Run 10 calls in {time.time() - start:,.2f} sec")
if __name__ == "__main__":
asyncio.run(test_asyncio_ratelimit())