使用Python提供高性能計算服務
前言
python具有豐富的庫,并且很容易作為膠水語言很容易與c/c++進行交互集成。
因此為了適應快速變化的業(yè)務和兼顧計算效率,在上層采用python作為server提供service,在底層采用c/c++進行計算是一種對于算法開發(fā)者非常適宜的方式。
python flask庫提供http接口以及相關(guān)demo頁面,gunicorn提供多核并行能力,底層c++庫提供單線程上的計算。
下面通過一個例子說明這種架構(gòu)。代碼地址:python_hps
準備
在實驗開始之前,需要安裝flask、gunicorn、apach bench tool等工具。
注:所有實驗均在linux系統(tǒng)中進行。測試機器為4核虛擬機。
- sudo pip install flask
- sudo pip install gunicorn
- sudo apt-get install apache2-utils
計算
計算部分模擬真實計算,因此計算量比較大,在我測試的虛擬機上單核單線程跑400ms左右。
c++核心計算部分,隨便寫的:
- API_DESC int foo(const int val)
- {
- float result = 0.0f;
- for(int c=0;c<1000;c++)
- {
- for(int i=0;i<val;i++)
- {
- result += (i);
- result += sqrt((float)(i*i));
- result += pow((float)(i*i*i),0.1f);
- }
- }
- return (int)result;
- }
python wrapper,采用ctypes:
- #python wrapper of libfoo
- class FooWrapper:
- def __init__(self):
- cur_path = os.path.abspath(os.path.dirname(__file__))
- self.module = ctypes.CDLL(os.path.join(cur_path,'./impl/libfoo.so'))
- def foo(self,val):
- self.module.foo.argtypes = (ctypes.c_int,)
- self.module.foo.restype = ctypes.c_int
- result = self.module.foo(val)
- return result
flask http API:
- @app.route('/api/foo',methods=['GET','POST'])
- def handle_api_foo():
- #get input
- val = flask.request.json['val']
- logging.info('[handle_api_foo] val: %d' % (val))
- #do calc
- result = fooWrapper.foo(val)
- logging.info('[handle_api_foo] result: %d' % (result))
- result = json.dumps({'result':result})
- return result
單核服務
首先測試python單核服務,同時也是單線程服務(由于python GIL的存在,python多線程對于計算密集型任務幾乎起反作用)。
- 啟動服務
在script目錄下執(zhí)行run_single.sh,即
- #!/bin/sh
- #python
- export PYTHONIOENCODING=utf-8
- #start server
- cd `pwd`/..
- echo "run single pocess server"
- python server.py
- cd -
- echo "server is started."
- 測試服務
另外打開一個終端,執(zhí)行script目錄下的bench.sh,即
- #!/bin/sh
- ab -T 'application/json' -p post.data -n 100 -c 10 http://127.0.0.1:4096/api/foo
- 測試結(jié)果
CPU運轉(zhuǎn)
ab測試結(jié)果
可以看出CPU只用了1個核,負載是2.44 request/second。
多核
- 啟動服務
在script目錄下執(zhí)行run_parallel.sh,即
- #!/bin/sh
- #python
- export PYTHONIOENCODING=utf-8
- #start server
- cd `pwd`/..
- echo "run parallel pocess server"
- gunicorn -c gun.conf server:app
- cd -
- echo "server is started."
其中g(shù)un.conf是一個python腳本,配置了gunicorn的一些參數(shù),如下:
- import multiprocessing
- bind = '0.0.0.0:4096'
- workers = max(multiprocessing.cpu_count()*2+1,1)
- backlog = 2048
- worker_class = "sync"
- debug = False
- proc_name = 'foo_server'
- 測試服務
另外打開一個終端,執(zhí)行script目錄下的bench.sh,即
- #!/bin/sh
- ab -T 'application/json' -p post.data -n 100 -c 10 http://127.0.0.1:4096/api/foo
- 測試結(jié)果
CPU運轉(zhuǎn)
ab測試結(jié)果
可以看出CPU用滿了4個核,負載是8.56 request/second。是單核的3.5倍左右,可以任務基本達成多核有效利用的的目的。
總結(jié)
使用flask、gunicorn基本可以搭建一個用于調(diào)試或者不苛責過多性能的服務,用于算法服務提供非常方便。本文提供該方案的一個簡單示例,實際業(yè)務中可基于此進行修改完善。