Skip to content

Instantly share code, notes, and snippets.

@penryu
Created December 16, 2019 22:57
Show Gist options
  • Save penryu/20a9e37aee22ff612577164a9ba2fa2b to your computer and use it in GitHub Desktop.
Save penryu/20a9e37aee22ff612577164a9ba2fa2b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import aiohttp
import asyncio
import statistics
import time
from aiohttp import request
from typing import Dict, List
COUNT: int = 50
URL: str = "https://api.ipify.org?format=json"
async def fetchPage(url: str) -> Dict[str, int]:
start_ns: int = time.time_ns()
async with aiohttp.request('GET', url) as resp:
text: str = await resp.text()
stop_ns: int = time.time_ns()
delta_ms = (stop_ns - start_ns) / 1000000
return {
'status': resp.status,
'time': delta_ms,
'size': len(text),
}
async def runAsync():
print("Starting async...")
start_ns: int = time.time_ns()
tasks = [fetchPage(f"{URL}?n={i}") for i in range(COUNT)]
responses = await asyncio.gather(*tasks)
stop_ns: int = time.time_ns()
delta_ms = (stop_ns - start_ns) / 1000000
times = [resp['time'] for resp in responses]
avg_time = statistics.mean(times)
total_time = sum(times)
print("Stopping async...")
print({"asyncAverage": avg_time, "asyncElapsed": delta_ms});
async def main():
await runAsync();
if __name__ == '__main__':
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment