我正在尝试学习使用Python的多处理模块。作为第一次测试,我想我会同时运行四个15秒的过程。我写了这个模块,我称之为“multiPtest.py”::
import time
import timeit
import multiprocessing
def sleepyMe(napTime):
time.sleep(napTime)
print "Slept %d secs" % napTime
def tester(numTests):
#Launch 'numTests' processes using multiProcessing module
for _ in range(numTests):
p = multiprocessing.Process(target=sleepyMe(15))
p.start() #Launch an 'independent' process
#p.join() ##Results identical with or without join
def multiTester():
#Time running of 4 processes
totTime = timeit.Timer('tester(4)', setup = 'from multiPtest import tester').repeat(1,1)
print "Total = ", totTime[0]
然而,当我跑步时,我得到了这些结果:
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from multiPtest import *
>>> multiTester()
Slept 15 secs
Slept 15 secs
Slept 15 secs
Slept 15 secs
Total = 60.0739970207
我原本期望总时间接近15秒,而不是60秒。我知道我有4个核心,因为我看了/ proc / cpuinfo:
~/Projects/PythonProjects$ cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 60
model name : Intel(R) Core(TM) i7-4900MQ CPU @ 2.80GHz
stepping : 3
microcode : 0x17
cpu MHz : 800.000
cache size : 8192 KB
physical id : 0
siblings : 8
core id : 0
cpu cores : 4
...
为什么我不能同时看到这4个睡眠者睡着了?我不应该在其他人睡着/忙碌时创建并启动新流程吗?我是否误解了多处理,Python的多处理模块或其他什么?
答案 0 :(得分:5)
在第
行p = multiprocessing.Process(target=sleepyMe(15))
您实际上已经调用 sleepyMe
并使用结果(None
)作为target
参数的值,因此等待15秒。尝试
p = multiprocessing.Process(target=sleepyMe, args=(15, ))
并在for循环之后将函数修改为join()
所有子进程,否则它将立即返回并且您将以总时间接近零结束。< / p>