Python 执行器 - 以参数作为参数传递函数

Python Executor - Passing function with argument as argument

我的目标是创建一个函数,我可以用它来衡量另一个函数的执行和资源使用情况。使用教程,我使用 Python 的 ThreadPoolExecutor 创建了以下内容:

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))

如果我将函数 foo 作为参数传递给函数 execute,它会打印出正确的结果并且 returns foo.

返回的值

如果我以同样的方式传递函数 bar,但 bar 本身需要一个参数,函数运行(打印 3 次)然后我得到以下错误:

result = self.fn(*self.args, **self.kwargs)
TypeError: 'int' object is not callable

经过一些测试,我卡住的部分似乎是将一个函数作为参数传递,如果该函数本身需要一个参数。我对ThreadPoolExecutor的理解,fn_thread对象封装了提交函数的执行。 result 对象应该简单地保存该执行的结果——我错过了什么,它无法处理传递给带参数的函数?

您正在提交

bar(0) 

而不是

bar, 0

为了澄清,请查看提交的签名: 提交(fn, *args, **kwargs)

的结果
bar(0)

是一个整数,执行程序不能调用整数,因为它不是 'callable',如错误消息所示。