为什么产卵过程会使计算快速运行两倍?
在我的精度5520上,以下计算大约需要10.4秒:
import time
before = time.time()
sum = 0
for i in range(1, 100000000):
sum += i
print(time.time() - before, sum)
在同一笔记本电脑上,以下仅需5.2秒:
import multiprocessing as mp
import time
def foo():
before = time.time()
sum = 0
for i in range(1, 100000000):
sum += i
print(time.time() - before, sum)
mp.Process(target=foo).start()
此结果是一致的。实际上,即使我同时运行cpu_count
同时进行处理,它也容纳(速度稍小)。
那么,为什么产卵过程会使计算快速运行的速度两倍?
The following computation takes about 10.4 seconds on my Precision 5520:
import time
before = time.time()
sum = 0
for i in range(1, 100000000):
sum += i
print(time.time() - before, sum)
On the same laptop, the following takes only 5.2 seconds:
import multiprocessing as mp
import time
def foo():
before = time.time()
sum = 0
for i in range(1, 100000000):
sum += i
print(time.time() - before, sum)
mp.Process(target=foo).start()
This result is consistent. In fact, it holds (with a slightly smaller speed-up factor) even if I run cpu_count
processes simultaneously.
So, why would spawning a process make computation run twice as fast?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是使计算快速的过程,而是在函数中运行计算。这是因为全局变量访问比使用CPYTHON解释器的局部变量访问速度慢。如果您只需在同一过程中运行
foo()
,则计算时间也降低了两倍。这是一个示例:注意覆盖内置函数
sum
有点危险,因为它可能会使用它破坏代码并导致奇怪的错误。It is not the process that make the computation fast, it is running the computation in a function. This is because global variable accesses are slower than local variable accesses using the CPython interpreter. If you simply run
foo()
in the same process, then the computation time is also twice lower. Here is an example:Note overwriting the built-in function
sum
is a bit dangerous as it may break codes using it and cause weird errors.