我需要计算某个代码块在多处理环境中花费的时间。我在这里使用示例代码进行解释。
import time
from multiprocessing import Process, Queue
class test():
def __init__(self):
self.processed_q = Queue()
def worker(slef,n):
#some code
#start of code for which I need to calculate time
st = time.time()
time.sleep(n)
et = time.time()-st
#end of code for which I need to calculate time
return et
#some code
def fun(self, n):
total_time = 0
for i in range(n):
total_time += self.worker(i)
self.processed_q.put(total_time)
def run(self):
now = time.time()
pids = []
for i in range(5):
p = Process(target=self.fun, args=(i,))
pids.append(p)
p.start()
for p in pids:
p.join()
tt = 0
while not self.processed_q.empty():
tt += self.processed_q.get()
print time.time()-now #total time taken by the program
print tt #total time taken by the worker function
t = test()
t.run()
我想在工作人员函数中找到一段代码所花费的时间,并希望对很多调用进行总结。让我们将此时间称为total_worker_time,并将程序所用的时间称为total_program_time。当我打印两者时,我发现total_worker_time大于total_program_time。这怎么可能?我是以错误的方式解释结果吗?
如果此方法在计算工作方法中的时间错误,请建议一些方法。如何根据计划的总时间表示工人职能所花费的总时间?