为什么产卵过程会使计算快速运行两倍?

发布于 2025-01-26 12:04:19 字数 611 浏览 6 评论 0原文

在我的精度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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

懷念過去 2025-02-02 12:04:19

这不是使计算快速的过程,而是在函数中运行计算。这是因为全局变量访问比使用CPYTHON解释器的局部变量访问速度慢。如果您只需在同一过程中运行foo(),则计算时间也降低了两倍。这是一个示例:

import time

def foo():
    before = time.time()
    sum = 0
    for i in range(1, 100000000):
        sum += i
    print(time.time() - before, sum)

# Slow (8.806 seconds)
before = time.time()
sum = 0
for i in range(1, 100000000):
    sum += i
print(time.time() - before, sum)

# Fast (4.362 seconds)
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:

import time

def foo():
    before = time.time()
    sum = 0
    for i in range(1, 100000000):
        sum += i
    print(time.time() - before, sum)

# Slow (8.806 seconds)
before = time.time()
sum = 0
for i in range(1, 100000000):
    sum += i
print(time.time() - before, sum)

# Fast (4.362 seconds)
foo()

Note overwriting the built-in function sum is a bit dangerous as it may break codes using it and cause weird errors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文