Python执行器-以参数作为参数传递函数
我的目标是创建一个可以用来衡量另一个函数的执行和资源使用情况的函数。通过一个教程,我使用Python的ThreadPoolExecutor创建了以下内容:Python执行器-以参数作为参数传递函数,python,python-3.x,python-multithreading,encapsulation,concurrent.futures,Python,Python 3.x,Python Multithreading,Encapsulation,Concurrent.futures,我的目标是创建一个可以用来衡量另一个函数的执行和资源使用情况的函数。通过一个教程,我使用Python的ThreadPoolExecutor创建了以下内容: from resource import * from time import sleep from concurrent.futures import ThreadPoolExecutor class MemoryMonitor: def __init__(self): self.keep_measuring =
from resource import *
from time import sleep
from concurrent.futures import ThreadPoolExecutor
class MemoryMonitor:
def __init__(self):
self.keep_measuring = True
def measure_usage(self):
max_usage = 0
u_run_time = 0
s_run_time = 0
while self.keep_measuring:
max_usage = max(max_usage, getrusage(RUSAGE_SELF).ru_maxrss)
u_run_time = max(u_run_time, getrusage(RUSAGE_SELF).ru_utime)
s_run_time = max(s_run_time, getrusage(RUSAGE_SELF).ru_stime)
sleep(0.1) # run this loop every 0.1 seconds
return [max_usage, u_run_time, s_run_time]
def execute(function):
with ThreadPoolExecutor() as executor:
monitor = MemoryMonitor()
stats_thread = executor.submit(monitor.measure_usage)
try:
fn_thread = executor.submit(function)
result = fn_thread.result()
print("print result")
print(result)
print("print result type")
print(type(result))
finally:
monitor.keep_measuring = False
stats = stats_thread.result()
print(stats)
return result
def foo():
i = 0
while i < 3:
print("foo")
i+=1
return 1
def bar(x):
while x < 3:
print("foobar")
x+=1
return 1
var = execute(foo)
print("Var = " + str(var))
var = execute(bar(0))
print("Var = " + str(var))
经过一些测试,如果函数本身需要一个参数,那么我遇到的问题似乎是将函数作为参数传递。据我对ThreadPoolExecutor的理解,fn_线程对象封装了提交的函数的执行。result对象应该只保存该执行的结果-我缺少什么,它不能处理传递带有参数的函数?您正在提交
bar(0)
而不是
bar, 0
要澄清,请查看提交人的签名:
提交(fn、*args、**kwargs)
结果
bar(0)
是一个整数,执行器不能调用整数,因为它不是“可调用的”,正如错误消息所示。就是这样-谢谢!我想这里的答案是重载execute函数,这样它就可以在两种情况下都接受调用。为便于将来参考,重载到def execute(function,args=None)并调整fn_线程调用以适应这两个选项是正确的路径。欢迎使用!如果将``def execute(函数,*args):…`根据你的定义。
bar(0)