看起来,使用顺序版本可能会更好。传统的看法是,在Python中,与I/O绑定的作业(文件读/写、联网)可以通过使用事件循环或多个线程来加速,而与CPU绑定的作业(如计算哈希)可以通过使用多个进程来加速。
然而,我把你的版本用
concurrent.futures
还有一个进程池,它不但没有加快进程,反而使进程慢了10倍。
以下是代码:
from concurrent import futures
import hashlib
import string
import random
import time
def hash_generator():
"""Return a unique hash"""
prefix = int(time.time())
suffix = (random.choice(string.ascii_letters) for i in range(10))
key = ".".join([str(prefix), str("".join(suffix))])
value = hashlib.blake2b(key.encode(), digest_size=6).hexdigest()
return value.upper()
def main(workers = None):
"""Iterating the hashes and printing the time it loaded"""
time_before = time.time()
with futures.ProcessPoolExecutor(workers) as executor:
worker_count = executor._max_workers
jobs = (executor.submit(hash_generator) for i in range(100000))
for future in futures.as_completed(jobs):
print(future.result())
time_after = time.time()
difference = time_after - time_before
print('Loaded in {0:.2f}sec with {1} workers'.format(difference, worker_count))
if __name__ == '__main__':
main()
对于多个进程,启动和停止不同进程以及进程间通信都会带来一些开销,这可能就是多进程版本比顺序版本慢的原因,尽管它使用了所有的CPU内核。
您还可以尝试使用集群将工作拆分到多台计算机上,和/或使用较低级别的语言编写算法(Go在我看来是个不错的选择)。但这是否值得你花时间,我不知道。