Python uses decorators to calculate function running time

Use the decorator to calculate the running time of the function without changing the function of the function. See the notes for details.

 

# -*- coding: UTF-8 -*-
"""
@File:  计算函数运行时间.py
@Author:authorized_keys
@Time:  2020/11/27 8:50
"""

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import time


def timeit(func):
    """

    :param func: 需要传入的函数
    :return:
    """

    def _warp(*args, **kwargs):
        """

        :param args: func需要的位置参数
        :param kwargs: func需要的关键字参数
        :return: 函数的执行结果
        """
        start_time = time.time()
        result = func(*args, **kwargs)
        elastic_time = time.time() - start_time
        print("The execution time of the function '%s'  is %.6fs\n" % (
            func.__name__, elastic_time))
        return result

    return _warp


@timeit
def my_ocr(img):
    # Set tesseract executable PATH
    pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
    # Image to string
    res_str = pytesseract.image_to_string(img)
    return res_str


if __name__ == '__main__':
    # Image path
    img_path = r"C:\Users\data\OCRImage\python-pip-with-local-wheel.png"

    # Read image
    image = Image.open(img_path)

    # Simple image to string
    print(my_ocr(image))

 

Guess you like

Origin blog.csdn.net/authorized_keys/article/details/110219719