Last active
August 29, 2015 14:06
-
-
Save BrianHicks/6f9f95cf5d49a66e6375 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler | |
import json | |
from multiprocessing import Pool, Queue | |
import random | |
import requests | |
from requests.packages.urllib3.exceptions import ProtocolError | |
import sys | |
import time | |
from timeit import timeit | |
PORTS = [8001, 8002, 8003, 8004] | |
class SquareHandler(BaseHTTPRequestHandler): | |
def do_GET(self): | |
self.wfile.write(self.client_address) | |
def do_POST(self): | |
data = self.rfile.read(int(self.headers['Content-Length'])) | |
try: | |
payload = float(data) | |
except ValueError: | |
self.wfile.write('not a number!') | |
return | |
result = payload ** 2 | |
print '%.2f -> %.2f' % (payload, result) | |
self.wfile.write(str(result)) | |
def run(port): | |
HTTPServer(('127.0.0.1', port), SquareHandler).serve_forever() | |
def isup(port): | |
try: | |
requests.get('http://127.0.0.1:%d' % port, timeout=0.1) | |
except ProtocolError: | |
return False | |
else: | |
return True | |
def waitforup(port): | |
while True: | |
if isup(port): | |
print '%d up' % port | |
return True | |
else: | |
time.sleep(0.1) | |
def square(num): | |
port = random.choice(PORTS) | |
return requests.post( | |
'http://127.0.0.1:%d/' % port, | |
headers={'Content-Type': 'text/plain'}, | |
data=str(num), | |
).content | |
if __name__ == '__main__': | |
pool = Pool(8) | |
servers = pool.map_async(run, PORTS) | |
pool.map(waitforup, PORTS) | |
count = int(sys.argv[-1]) | |
xs = pool.map(square, range(count)) | |
ints = pool.map(float, xs) | |
print sum(ints) |
This file contains hidden or 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
⇒ python multi.py 10 | |
8002 up | |
8004 up | |
8001 up | |
8003 up | |
3.00 -> 9.00 | |
2.00 -> 4.00 | |
0.00 -> 0.00 | |
1.00 -> 1.00 | |
6.00 -> 36.00 | |
5.00 -> 25.00 | |
7.00 -> 49.00 | |
4.00 -> 16.00 | |
8.00 -> 64.00 | |
9.00 -> 81.00 | |
285.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment