使用多处理来利用CPU的所有核心

时间:2016-02-07 21:54:06

标签: python process multiprocessing flops multiple-processes

我正在尝试计算我的CPU可以执行的每秒浮点运算次数,所以我编写了以下程序:

import time
import sys
from multiprocessing import Process


numOfLoops = 10000000

if (len(sys.argv) != 2):
    print "Correct Usage: python cpu.py 'no_of_processes'"
    sys.exit()

#function for each process
def fpOps():
    a = float(0.0)
    for i in xrange(0, numOfLoops):
        a += 0.5
        #print a #for debugging purpose

processes = []
numOfProcesses = int(sys.argv[1])
numOfOps = numOfLoops * numOfProcesses

for i in xrange(0, numOfProcesses):
    processes.append(Process(target=fpOps))

start = time.time()
for process in processes:
    process.start()
for process in processes:
    process.join()
end = time.time()

execTime = end - start
print "Exec Time " , execTime


FLOPS = (float(numOfOps/execTime))
print "FLOPS : " , FLOPS

程序计算执行'n'次浮点运算所需的时间(execTime),'n / execTime'给出我想要的FLOPS值。

但是,随着我增加进程的数量,FLOPS值会减少。我期待它减少,因为进程每秒执行更多的操作,因为它们并行运行。我究竟做错了什么??

0 个答案:

没有答案