• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

describe

Decorators are a special class of Python syntax that can be written on the top line of functions that are decorated as @decorator_name. Like this:

@decorator_name
def func():
    # do something
    pass
Copy the code

The purpose of a decorator is to be able to do some processing before and after a function is executed, and such processing is usually generic and needs to be wrapped in multiple functions. Therefore, using decorators can effectively avoid code duplication and improve code readability.

The task of this topic is a decorator that requires you to implement a timer. The name of this decorator is named Timer. We wrap the timer around any function, so that when the function is called, the execution time of the function is automatically recorded and printed. Like this:

@timer
def func():
    pass
Copy the code

Your task is to edit the decorators.py file, implement a timer decorator, and print out the name of the function and the elapsed time.

**

Always remember to return functions inside a decorator.

The sample

This problem does not require any input data, you can look at the main.py file, your code should be printed after executing Python main.py

Function func_A cost 0.1 seconds Function func_b cost 0.2 secondsCopy the code

challenge

It must be implemented as a decorator and cannot be bypassed by other methods

Answer key

A decorator is a function that takes a function (or class) as an argument and returns a function (or class) as a value

Time.time () gets the current time.

Format formats data results.

import time # write your code here # you need to implement a decorator named timer # the decorator will timer the Decorated function and print the name of the # function and the running time in format 'function a cost 0.1 seconds' def  timer(func): def warpper(*args,**kwargs): startTime=time.time() func(*args,**kwargs) endTime = time.time() costTime=round(endTime-startTime,1) print("function {func} cost {endTime} seconds".format(func=func.__name__,endTime=costTime)) return warpper @timer def func(): passCopy the code