大部分执行时间花在执行两个独立函数评估上的代码显然是使用两个 CPU 的候选者。我知道如何在 Python 中使用 multiprocessing
来完成它,但只有在程序的入口点添加成语 if __name__ == '__main__':
。现代 Python(撰写本文时为 3.8.3)是否有更简单的方法?没有there看起来很简单。
要求:调用代码不做任何改动,也没有单独的文件。 import
一些帮助程序很好,但我不想 pip
。
密码学领域的示例应用和基准:
def rsacrt(p,q,dp,dq,qi,x):
# most of the time is spent in the following two lines
u = pow(x,dp,p)
v = pow(x,dq,q)
return (u-v)*qi%p*q+v
# test and benchmark the above
import time
e,p,q = 3, 5**3528+12436, 7**2918+27562
n,dp,dq,qi = p*q, pow(e,-1,p-1), pow(e,-1,q-1), pow(q,-1,p)
x = 42
t = time.time()
y = rsacrt(p,q,dp,dq,qi,x)
t = time.time()-t
if pow(y,e,n)!=x: print("# wrongo, spasmoid!")
print("duration of rsacrt:",(int)(t*1000.),"ms")
所示操作是 RSA 签名生成和 RSA 解密中的一个瓶颈。参数故意设置得很高(16384 位 RSA,而不是通常的 2048 位),因此执行时间以秒为单位,前两个 pow
的执行时间 >98%。这是为了说明并行执行很重要的真实案例,而不是作为如何执行 RSA 的示例:pow
有快速替代方案,并且此代码缺乏侧信道保护。
注意:此代码需要一个 Python 版本,其中 pow
可以计算模逆。其中包括 Python 3.8.x。 Try it online! .
补充:在 Python 3 下工作的代码要大得多,请参阅其他 Try it online! .
最佳答案
当使用multiprocessing
时,if __name__ == '__main__'
保护仅在模块的顶级范围内需要。 multiprocessing
和派生模块可以直接在函数中使用。
使用 multiprocessing.Pool
或 concurrent.futures.ProcessPoolExecutor
对于简洁的 API:
def rsacrt(p,q,dp,dq,qi,x):
with concurrent.futures.ProcessPoolExecutor() as executor:
u, v = executor.map(pow, *zip((x, dp, p), (x, dq, q)))
return (u-v)*qi%p*q+v
这大致将 rsacrt
加速了 2 倍。
关于python - Python 中两个函数的简单并行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62296280/