[Python3] Define a decorator to measure the execution time of a function

I felt that it would be possible to measure the execution time of a function just by adding a decorator, so I tried it. (I think it's already in the package)

Implementation example

Since I am using f-string soberly, Python 3.6 or higher is required, but I think that 2.7 will work with some modifications.

Defining a decorator that measures the execution time of a function


import time

def calc_time(message='', parser=None):
    def _calc_time(func):
        import functools

        @functools.wraps(func)
        def wrapper(*args, **kargs):
            start = time.time()
            ret = func(*args, **kargs)
            if parser:
                parsed_message = parser(message, *args, **kargs)
                print(
                    f'end time : {time.time() - start:0.4} sec : {parsed_message}')
            else:
                print(f'end time : {time.time() - start:0.4} sec : {message}')
            return ret
        return wrapper
    return _calc_time

I think there are cases where I want to display a message that uses a function argument, so I am making it possible to pass a function object for message processing.

Example of use

test.py


import time


def message_parser(message, *args, **kargs):
    return f"{message} and {args[0]}"


def calc_time(message='', parser=None):
    def _calc_time(func):
        import functools

        @functools.wraps(func)
        def wrapper(*args, **kargs):
            start = time.time()
            ret = func(*args, **kargs)
            if parser:
                parsed_message = parser(message, *args, **kargs)
                print(
                    f'end time : {time.time() - start:0.4} sec : {parsed_message}')
            else:
                print(f'end time : {time.time() - start:0.4} sec : {message}')
            return ret
        return wrapper
    return _calc_time


@calc_time()
def test1():
    time.sleep(0.2)
    print('call test1')


@calc_time('something message')
def test2():
    time.sleep(0.2)
    print('call test2')


@calc_time('something message', parser=message_parser)
def test3(something_args):
    time.sleep(0.2)
    print('call test3')


@calc_time('something message',
           parser=lambda message, *args, **kargs: f"{message} and {args[0]}")
def test4(something_args):
    time.sleep(0.2)
    print('call test4')

@calc_time('something message',
           parser=lambda message, *args, **kargs: f"{message} and {kargs['something_args']}")
def test5(something_args):
    time.sleep(0.2)
    print('call test4')

@calc_time(parser=lambda message, *args, **kargs: f"{args[0]}")
def test6(something_args):
    time.sleep(0.2)
    print('call test4')

def main():
    test1()
    test2()
    test3('something args')
    test4('something args')
    test5(something_args='something args')
    test6('something args')

if __name__ == '__main__':
    main()

Execution example


$ python test.py
call test1
end time : 0.2001 sec : 
call test2
end time : 0.2 sec : something message
call test3
end time : 0.2001 sec : something message and something args
call test4
end time : 0.2 sec : something message and something args
call test4
end time : 0.2 sec : something message and something args
call test4
end time : 0.2008 sec : something args

reference

About Python Decorators-Qiita [python] Use functools.wrap () with decorator --logging.info (self) [Python: How to make and use various decorators, and the essence | CUBE SUGAR STORAGE](http://momijiame.tumblr.com/post/86112194941/python-%E8%89%B2%E3%80%85%E3% 81% AA% E3% 83% 87% E3% 82% B3% E3% 83% AC% E3% 83% BC% E3% 82% BF% E3% 81% AE% E4% BD% 9C% E3% 82% 8A%E6%96%B9%E3%81%A8%E4%BD%BF%E3%81%84%E6%96%B9%E3%81%9D%E3%81%97%E3%81%A6% E6% 9C% AC% E8% B3% AA)

Recommended Posts

[Python3] Define a decorator to measure the execution time of a function
Python: I want to measure the processing time of a function neatly
Measure function execution time in Python
A function that measures the processing time of a method in python
[Python] A simple function to find the center coordinates of a circle
Function execution time (Python)
Get the caller of a function in Python
How to measure execution time with Python Part 1
How to measure execution time with Python Part 2
I made a function to see the movement of a two-dimensional array (Python)
I made a tool to estimate the execution time of cron (+ PyPI debut)
How to pass the execution result of a shell command in a list in Python
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
A programming beginner tried to find out the execution time of sorting etc.
Python Note: The mystery of assigning a variable to a variable
How to execute a schedule by specifying the Python time zone and execution frequency
How to unit test a function containing the current time using freezegun in python
Add a function to tell the weather of today to slack bot (made by python)
Try to get the function list of Python> os package
Measure the execution result of the program in C ++, Java, Python.
[Python] Make the function a lambda function
Python (from first time to execution)
I made a function to crop the image of python openCV, so please use it.
How to pass the execution result of a shell command in a list in Python (non-blocking version)
[Introduction to Python] How to split a character string with the split function
A story that struggled to handle the Python package of PocketSphinx
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
How to check the memory size of a variable in Python
I tried to make a regular expression of "time" using Python
How to check the memory size of a dictionary in Python
Create a function to get the contents of the database in Go
[python] A note that started to understand the behavior of matplotlib.pyplot
[Python] A program that rotates the contents of the list to the left
Create a Python function decorator with Class
Measure the relevance strength of a crosstab
[Python3] Rewrite the code object of the function
[python] [meta] Is the type of python a type?
The story of blackjack A processing (python)
[Python] Explains how to use the range function with a concrete example
[Python] A program that calculates the number of socks to be paired
Various methods to numerically create the inverse function of a certain function Introduction
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to create a wrapper that preserves the signature of the function to wrap
[Introduction to Python] How to write a character string with the format function
Python code to determine the monthly signal of a relative strength investment
Get a datetime instance at any time of the day in Python
I made a program to check the size of a file in Python
[Python] Note: A self-made function that finds the area of the normal distribution
Python function decorator
How to calculate the volatility of a brand
Draw a graph of a quadratic function in Python
Prepare the execution environment of Python3 with Docker
To execute a Python enumerate function in JavaScript
Setting to output the log of cron execution
Make a copy of the list in Python
A clever way to time processing in Python
A note about the python version of python virtualenv
[Python] A rough understanding of the logging module
Output in the form of a python array
At the time of python update on ubuntu
A python amateur tries to summarize the list ②