Python :装饰器中的 lambda 函数详细信息



尝试在我正在计算的装饰中添加执行进程(测试,a,b(名称。

最终预期日志:

Process **a** elapsed time :3.8 || Rowcount=1833
Process **test** elapsed time :7.8 || Rowcount=1133

法典

import time
from queries import a,b,test
def elapsedTimeTracker_decorator(func):
def wrapper():
start_time = time.time()
func()
print(test)
end_time = time.time()
elapsed_time = end_time - start_time
print('elapsed_time:'+ str(elapsed_time) +'||' + 'RowCount:' + str(cursor.rowcount))
return wrapper

print "Process a started"
elapsedTimeTracker_decorator(lambda: cursor.execute(a))()
print "Process Test started"
elapsedTimeTracker_decorator(lambda: cursor.execute(Test))()
print "Process b started"
elapsedTimeTracker_decorator(lambda: cursor.execute(b))()

a,b&test由SQL Update Query组成

test = """INSERT INTO users
select * from user_all where user_id=54549172 """

如果您希望为不带参数的修饰 lambda 打印额外的数据,那么您必须将其传递给您的装饰器:

def elapsedTimeTracker_decorator(func, test):
def wrapper():
start_time = time.time()
func()
print(f'Process {test} elapsed time: {time.time() - start_time} || Rowcount={cursor.rowcount}')
return wrapper
elapsedTimeTracker_decorator(lambda: cursor.execute(test), test)()

除此之外,我不知道你的test应该从哪里来。如果这不是一个合适的解决方案,请详细说明更多详细信息。

编辑:根据提供的最新信息,很明显您不需要使用 lambda,也不需要使用带有内部包装器的装饰器。您可以简单地使用一个简单的函数来调用给定的函数,其中包含提供的参数和关键字,这些函数将处理调用以及打印执行时间。例如:

from time import time as now
def time_call(func, *args, **kwargs):
cur = now()
func(*args, **kwargs)
print(
f'Executing {func.__qualname__}({repr(args)[1:-1]}, ' +
f'{"".join(f"{k}={v}" for k, v in kwargs.items())}) took ' +
f'{now() - cur} seconds.'
)
def test(foo, bar, baz):
pass
time_call(test, 'foo', 'bar', baz=None)

这将打印类似以下内容:

Executing test('foo', 'bar', baz=None) took 0.0 seconds.

最新更新