asyncio
select, poll, epoll, kqueue...
def fetch_track(track_id):
resp = requests.get(
'https://api.kkbox.com/v1.1/tracks/'+track_id,
params={'territory': 'TW'},
headers={'Authorization': 'Bearer ' + TOKEN})
return resp.json()
def fetch_tracks_briefly(track_ids):
results = list()
for track_id in track_ids:
track_info = fetch_track(track_id)
results.append((
track_info['id'],
track_info['name'],
track_info['album']['artist']['name']))
return results
def main():
with open('60_tracks', 'r') as f:
track_ids = [track_id.strip() for track_id in f]
start = time.time()
results = fetch_tracks_brief(track_ids)
end = time.time()
for track_brief in results:
print('{} {} {}'.format(*track_brief))
print('Fetched {} tracks in {:.3f} seconds.'.format(
len(results), end-start))
Number of track | Time (sec) |
---|---|
20 tracks | 1.97 |
40 tracks | 3.94 |
60 tracks | 6.23 |
async def fetch_track(track_id):
async with aiohttp.request('GET',
'https://api.kkbox.com/v1.1/tracks/'+track_id,
params={'territory': 'TW'},
headers={'Authorization': 'Bearer ' + TOKEN}) as resp:
return await resp.json()
def fetch_track(track_id):
resp = requests.get(
'https://api.kkbox.com/v1.1/tracks/'+track_id,
params={'territory': 'TW'},
headers={'Authorization': 'Bearer ' + TOKEN})
return resp.json()
async def fetch_tracks_brief(track_ids):
results = list()
futures = asyncio.as_completed(
[fetch_track(track_id) for track_id in track_ids])
for future in futures:
track_info = await future
results.append((
track_info['id'],
track_info['name'],
track_info['album']['artist']['name']))
return results
def fetch_tracks_briefly(track_ids):
results = list()
for track_id in track_ids:
track_info = fetch_track(track_id)
results.append((
track_info['id'],
track_info['name'],
track_info['album']['artist']['name']))
return results
def main():
with open('60_tracks', 'r') as f:
track_ids = [track_id.strip() for track_id in f]
loop = asyncio.get_event_loop()
start = time.time()
results = loop.run_until_complete(
fetch_tracks_brief(track_ids))
end = time.time()
for track_brief in results:
print('{} {} {}'.format(*track_brief))
print('Fetched {} tracks in {:.3f} seconds.'.format(
len(results), end-start))
def main():
with open('60_tracks', 'r') as f:
track_ids = [track_id.strip() for track_id in f]
start = time.time()
results = fetch_tracks_brief(TOKEN, track_ids)
end = time.time()
for track_brief in results:
print('{} {} {}'.format(*track_brief))
print('Fetched {} tracks in {:.3f} seconds.'.format(
len(results), end-start))
Number of track | Time (sec) |
---|---|
20 tracks | 0.15 |
40 tracks | 0.20 |
60 tracks | 0.24 |
Tulip: Async I/O for Python 3 - Guido van Rossum
Fan-in and Fan-out - Brett Slatkin