Skip to main content
 首页 » 编程设计

python之为什么我的所有进程不是同时启动

2025年05月04日14TianFang

我有一个将一堆数字相加的过程:

def slow(x): 
    num = 0 
    for i in xrange(int(1E9)): 
        num += 1 

我开始了其中的 500 个。

for x in range(500): 
    out.write("Starting slow process - " + str(datetime.now()) + "\n") 
    p = multiprocessing.Process(target = slow, args = (x, )) 
    p.start() 

我希望所有进程同时启动,因为我的计算机上允许的最大进程数大于 500。

user@computer$ cat /proc/sys/kernel/pid_max 
32768 

但是,一个进程的开始时间和下一个进程的开始时间之间存在短暂的延迟。

Starting slow process - 2015-05-14 16:41:35.276839 
Starting slow process - 2015-05-14 16:41:35.278016 
Starting slow process - 2015-05-14 16:41:35.278666 
Starting slow process - 2015-05-14 16:41:35.279328 
Starting slow process - 2015-05-14 16:41:35.280053 
Starting slow process - 2015-05-14 16:41:35.280751 
Starting slow process - 2015-05-14 16:41:35.281444 
Starting slow process - 2015-05-14 16:41:35.282094 
Starting slow process - 2015-05-14 16:41:35.282720 
Starting slow process - 2015-05-14 16:41:35.283364 

随着我们启动更多进程,这种延迟会变得更长:

Starting slow process - 2015-05-14 16:43:40.572051 
Starting slow process - 2015-05-14 16:43:41.630004 
Starting slow process - 2015-05-14 16:43:42.716438 
Starting slow process - 2015-05-14 16:43:43.270189 
Starting slow process - 2015-05-14 16:43:44.336397 
Starting slow process - 2015-05-14 16:43:44.861934 
Starting slow process - 2015-05-14 16:43:45.948424 
Starting slow process - 2015-05-14 16:43:46.514324 
Starting slow process - 2015-05-14 16:43:47.516960 
Starting slow process - 2015-05-14 16:43:48.051986 
Starting slow process - 2015-05-14 16:43:49.145923 
Starting slow process - 2015-05-14 16:43:50.228910 
Starting slow process - 2015-05-14 16:43:50.236215 

什么可能导致这种现象?

请您参考如下方法:

您正在启动 500 个进程;每一个你都要求数到一百万来旋转。我不确定为什么您会惊讶于这需要时间?

启动 500 个进程即使什么都不做也会花费一些时间,但是当每个进程都使用 python 数到一百万时,几乎一两秒就会过去。这些其他进程现在将争夺 CPU 时间,并不能保证进行生成的进程会赢得这场比赛并立即生成其余进程。

编辑:你还对系统进行了 500 次调用以获取时间并打印它,这也需要一些时间,如果你只在开始和完成产卵时打印时间,我怀疑这也会加快速度。

我怀疑如果您将计数循环替换为 sleep 调用或类似性质的东西,这会更快,因此您所看到的根本不仅仅是启动流程的时间。