起因:

在处理程序的过程中,老是达不到要求的速度,比如昨天的数据还没处理完,今天的数据又来了。

 

解决方法:

采用的方法可以有多种,这里介绍下多进程。

为了防止启动过多进程而卡死机器,进程池是个不错的方案。

在设置进程池容量的时候,最好是和机器的核心数一样。

 

代码实例:

from multiprocessing import Pool
import time


def store_es2(**kwargs):
    source = kwargs.get("data_source", None)
    print("Now handling source:", source)
    time.sleep(10)
    return True


if __name__ == "__main__":
    t1 =time.time()
    p = Pool(4)
    S = ["source1", "source2", "source4", "source5", "source6"]
    for i in S:
        res = p.apply_async(store_es2, kwds={"data_source":i})
        print(res)
    p.close()
    p.join()
    print("use time:{:.3f}".format(time.time()-t1))
    print("done!")

 

输出:

$ python multipool.py 
<multiprocessing.pool.ApplyResult object at 0x7f75b88e4ac8>
<multiprocessing.pool.ApplyResult object at 0x7f75b88e4ba8>
<multiprocessing.pool.ApplyResult object at 0x7f75b88e4cc0>
Now handling source: source1
<multiprocessing.pool.ApplyResult object at 0x7f75b88e4d68>
<multiprocessing.pool.ApplyResult object at 0x7f75b88e4e10>
Now handling source: source2
Now handling source: source4
Now handling source: source5
Now handling source: source6
use time:20.053
done!

 

大家如有更好的方法,欢迎在下方留言,或加微信:wst_ccut