Python 手写代码面试题, 写一个 Python 记录函数执行时间的装饰器
Python 手写代码面试题, 写一个 Python 记录函数执行时间的装饰器
QA
Step 1
Q:: 写一个 Python 记录函数执行时间的装饰器
A::
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Function {func.__name__} took {elapsed_time:.4f} seconds to execute.")
return result
return wrapper
@timing_decorator
def example_function():
time.sleep(2)
print("Function executed")
example_function()
Step 2
Q:: 为什么需要使用装饰器来记录函数执行时间?
A:: 装饰器可以在不修改函数本身的情况下增强函数的功能。这使得代码更加简洁和模块化,便于维护和扩展。在性能调优过程中,了解函数的执行时间有助于识别性能瓶颈。
Step 3
Q:: 如何修改装饰器来记录多次调用的平均执行时间?
A::
import time
from functools import wraps
class TimingDecorator:
def __init__(self, func):
self.func = func
self.total_time = 0
self.call_count = 0
def __call__(self, *args, **kwargs):
start_time = time.time()
result = self.func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
self.total_time += elapsed_time
self.call_count += 1
average_time = self.total_time / self.call_count
print(f"Function {self.func.__name__} took {elapsed_time:.4f} seconds to execute (average {average_time:.4f} seconds over {self.call_count} calls).")
return result
@TimingDecorator
def example_function():
time.sleep(1)
print("Function executed")
example_function()
example_function()
Step 4
Q:: 装饰器可以应用在哪些场景中?
A:: 装饰器可以应用于日志记录、权限验证、性能分析、缓存、事务处理等场景,提升代码的可读性和复用性。
用途
面试中考察装饰器和性能分析的内容是为了了解候选人对Python高级特性的掌握情况,特别是在代码优化和性能调优方面的能力。在实际生产环境中,记录函数执行时间的需求非常常见,特别是在需要优化代码性能或者监控系统性能时。\n相关问题
🦆
请解释一下 Python 中的装饰器是什么,以及它们是如何工作的?▷
🦆
Python 中的装饰器是如何实现函数参数传递的?▷
🦆
装饰器如何用于类方法?请举例说明.▷
🦆
如何编写一个装饰器来缓存函数的结果,以提升性能?▷
🦆
什么是functools.wraps,为什么要在装饰器中使用它?▷