SoFunction
Updated on 2024-11-17

Python Decorator and Threading Combined to Improve Interface Access Efficiency Methods

Review the basic usage of decorators

Decorators are essentially closures, a kind of python syntactic sugar

def outer(fun):
    def inner(*args,**kwargs):
        return fun(*args,**kwargs)
    return inner
# Decorate the two functions with decorators
@outer
def num1():
    print('a')
@outer
def num2():
    print('b')
if __name__ == '__main__':
    print(num1.__name__)
    print(num2.__name__)
The output of the above code:
inner
inner
Characteristics of the decorator:Using a custom decorator changes the function name of the decorated function,Generally decorators don't have to take this into account,But if more than one function is decorated by two decorators it will report an error,Because the function name is the same

Solution: Introduce

import functools
def outer(fun):
    @(fun)
    def inner(*args,**kwargs):
        return fun(*args,**kwargs)
    return inner

The above code outputs the result:
num1
num2

Applications in real business

Defining decorators for multithreading

def async_call(fun):
    def wrapper(*args, **kwargs):
        Thread(target=fun, args=args, kwargs=kwargs).start()
    return wrapper

This decorator can be added to interfaces that need to improve efficiency
Because threads normally execute faster than processes.

You can use decorators to test and count function runtimes

import time
def coast_time(func):
    def fun(*args, **kwargs):
        t = time.perf_counter()
        result = func(*args, **kwargs)
        print(f'func {func.__name__} coast time:{time.perf_counter() - t:.8f} s')
        return result
    return fun

This decorator is interested in friends can be saved, the future performance of the interface can be directly taken over to use!

from time import sleep
from time import time
import time
from threading import Thread
# It's a decorator for counting time #
def coast_time(func):
    def fun(*args, **kwargs):
        t = time.perf_counter()
        result = func(*args, **kwargs)
        print(f'func {func.__name__} coast time:{time.perf_counter() - t:.8f} s')
        return result
    return fun
# This is a decorator to create threads, if you are interested you can save it and use it directly!
def async_call(fun):
    def wrapper(*args, **kwargs):
        Thread(target=fun, args=args, kwargs=kwargs).start()
    return wrapper
@coast_time
@async_call
def hello():
    print('start')
    sleep(2)
    print('end')
    return
if __name__ == "__main__":
    hello()

Running time without creating a thread is: 2s+
Time to use thread decorator: 0.0003s

can be introduced to prevent function names from being changed when decorating multiple functions

Above is Python decorator combined with threads to improve the efficiency of interface access methods in detail, more information about Python to improve the efficiency of interface access please pay attention to my other related articles!