我想创建一个函数来计算其他函数的执行时间,但是当我这样做时,出现类似以下错误:'int'对象不可调用。这是什么问题?
import time
def square(x):
return x**2
def timer(func):
t1 = time.perf_counter()
func()
t2 = time.perf_counter()
print(t2-t1)
timer(square(5))
答案 0 :(得分:1)
也可以修改代码以使其正常工作,但是在将函数作为第一个参数传入后,您必须将TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, "templates"),],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request", # <=========== that must be there
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
的参数传入square()
。>
timer()
使用def timer(func, *args, **kwargs):
t1 = time.perf_counter()
func(*args, **kwargs)
t2 = time.perf_counter()
print(t2-t1)
timer(square, 5)
和*args*
让我们处理具有任意参数的函数。
更方便的方法是使用装饰器。它返回原始函数周围的包装函数。您不必为了进行特定功能计时而进行大量更改。这是一个示例:
**kwargs
要使用它,只需执行以下操作:
def timer(func):
def wrapper(*args, **kwargs):
func_name = func.__name__
print(f"Starting {func_name}")
t1 = time.perf_counter()
output = func(*args, **kwargs)
t2 = time.perf_counter()
print(f"Total time for {func_name}: {t2 - t1:.3f} s\n")
return output
return wrapper
或者:
@timer
def square(x):
return x**2
square(5)
答案 1 :(得分:0)
square(5)
返回25
;所以您正在尝试对数字运行计时器;)
请尝试:
import time
def timer(func):
def f(args):
t1 = time.perf_counter()
ret = func(args)
t2 = time.perf_counter()
print('execution time: {}'.format(t2-t1))
return ret
return f
def square(x):
return x**2
timedSqure = timer(square)
res = timedSqure(5)
print(res)
此外,我建议您在python中学习decorators,因为使用装饰器,您可以通过声明以下内容使其更加优雅:
@timer
def square(x):
return x**2
请参见repl here
最后,根据@Heap Overflow的评论:对运行得如此快的东西计时没有意义。如果要对函数进行基准测试,则应使用timeit
答案 2 :(得分:0)
您的timer
希望有一个函数要调用,但是您给它的结果是已经调用一个函数的结果(结果不是函数)。
您可以改为使用timer(lambda: square(5))
。然后,是您的timer
函数执行(匿名)函数,并按预期执行表达式square(5)
。