为什么在我的Python代码中并行比平常慢?

时间:2015-10-18 20:05:03

标签: python

我想用Python测试并行代码,所以我编写了以下代码。

__author__ = 'Zir'
import numpy as np
from joblib import Parallel, delayed
import time

def f(x):
    h = np.random.rand()
    return x + h

if __name__ == '__main__':
    s1 = time.time()
    y = Parallel(n_jobs=3)(delayed(f)(x) for x in range(100000))
    e1 = time.time() - s1
    s2 = time.time()
    y = []
    for x in range(100000):
        y.append(f(x))
    e2 = time.time() - s2
    print e1, e2

输出为:4.08599996567 0.0699999332428表示for循环要快得多。为什么呢?

0 个答案:

没有答案