获取我触发的新流程的开始时间

时间:2014-01-17 17:23:36

标签: python multiprocessing

我在python中使用Multiprocessing模块并触发许多进程。有没有办法可以找出我触发的每个流程的START TIME?

由于流程被快速触发,我希望以毫秒甚至纳秒来获得时间来区分每个流程。 这是我的一段代码,

import multiprocessing
import time

def myProcess(processName):
    print "This is a method that will run in parallel: processName"
    time.sleep(120)

num = 100

for n in range(1,num):
    processName = "Process %s" % n
    proc = multiprocessing.Process(target=myProcess,args=(processName))
    proc.start()
    proc.join()

print "process startTime: %s " ?????

3 个答案:

答案 0 :(得分:0)

不要那样做。 multiprocessing.Process个对象具有pid属性 - 进程ID,它是操作系统级别的进程唯一标识符 。请改用它。

答案 1 :(得分:0)

您可以编写自己的包装类来记录startime -

class Proc(object):
    def __init__(self,cmd)
        self.cmd = cmd

    def run(self):
        proc = multiprocessing.Process(target=myProcess,args=(args))
        self.startime = datetime.datetime.now()
        proc.start()
        proc.join()  // Don't use this if you don't want to wait.


procobj = Proc(cmd)
procobj.run()
procobj.startime // gives you starttime

答案 2 :(得分:0)

您可以将Queue传递给流程并将开始时间保存在那里:

def myProcess(processName,times):
    print "This is a method that will run in parallel: processName"
    times.put((processName,time.time()))
    time.sleep(120)

q = multiprocessing.Queue()
for n in range(num):
    processName = "Process %s" % n
    proc = multiprocessing.Process(target=myProcess,args=(processName,q))
    proc.start()
    proc.join()

while not q.empty():
    a = q.get()
    print a
    "%s startTime: %f" % a