Created
January 31, 2017 08:31
-
-
Save haasad/af251cfe02d065de7079189b18841b79 to your computer and use it in GitHub Desktop.
Run parallel requests with ThreadPoolExecutor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"# Run parallel requests with ThreadPoolExecutor" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"import concurrent\n", | |
"import requests" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"10 loops, best of 3: 51 ms per loop\n" | |
] | |
} | |
], | |
"source": [ | |
"%timeit response = requests.get('http://www.google.ch')" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"CPU times: user 229 ms, sys: 35.7 ms, total: 265 ms\n", | |
"Wall time: 2.9 s\n" | |
] | |
} | |
], | |
"source": [ | |
"%%time\n", | |
"response_list = []\n", | |
"for _ in range(50):\n", | |
" response_list.append(requests.get('http://www.google.ch'))" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 4, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"def get_website(website):\n", | |
" return requests.get(website)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 5, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"CPU times: user 165 ms, sys: 35 ms, total: 200 ms\n", | |
"Wall time: 203 ms\n" | |
] | |
} | |
], | |
"source": [ | |
"%%time\n", | |
"with concurrent.futures.ThreadPoolExecutor() as p:\n", | |
" response_list_parallel = list(p.map(get_website, ('http://www.google.ch' for _ in range(50))))" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python [conda env:bw]", | |
"language": "python", | |
"name": "conda-env-bw-py" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.5.2" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment