An easy way to view the time taken in Python and a smarter way to improve it

I use it a lot but forget it so I output it to remember I intend to write it easily for beginners

For busy people

We have published a decorator on Github that displays the processing time of the function. ** Just install with pip, import and add a decorator to the function you want to measure the processing time! ** ** Please use it

Main subject: Easy (but unfortunate?) Method

Use Python standard time.time () time.time () returns the current UNIX time as a floating point number, so you can take the difference between the time before and after processing.

main.py



import time

start = time.time() #Record start time
"""

Write the process you want to measure the time

"""
end = time.time() #Record the end time
proc_time = end - start #Calculate processing time

print(f"process took {proc_time} seconds") #Show processing time

Just this

A little disappointing?

Smart improvements with decorators

Make the code above smarter by recreating it into a decorator that measures the processing time of the function

mytools.py



import time
from functools import wraps

def fntime(fn) :
    @wraps(fn)
    def wrapper(*args, **kwargs) :
        start = time.time()
        result = fn(*args, **kwargs)
        end = time.time()
        proc_time = end - start
        print(f"function:{fn.__name__} took {proc_time} seconds")
        return result
    return wrapper

(´-`) .. oO (I'm not going to do it now, but I'd like to explain the decorator someday ...)

main.py



from mytools import fntime

@fntime
def my_process() :
    """
Processing you want to measure
↓ Processing example
    """
    sum = 0
    for i in range(100000000) :
        sum += i

my_process() #Execute the process you want to measure

If you put these two files in the same directory and run main.py

Terminal


$ python main.py
function:my_process took 6.954758167266846 seconds

It will be displayed like this Beautiful. Great. cute. Like.

However, this still has some unfortunate drawbacks. If you try to use @ fntime in another directory, you have to copy and pastemytools.py to that directory.

So I published the code on Github so that I don't have to do that. Just install it with pip, import it and add @fntime to the function! The nice thing about Python is that you can easily avoid reinventing the wheel. Please use it (´-`) .. oO (The Github code is a little easier to see, such as coloring the function name and time, and arranging them vertically.)

Please also follow twitter! Do you usually have a lot of machine learning or Python tweets? As a fledgling engineer, there are many basic posts

I will be posting more and more qiita from now on! I want to make more simple tools like this

Give me LGTM!

Recommended Posts

An easy way to view the time taken in Python and a smarter way to improve it
A clever way to time processing in Python
It is easy to execute SQL with Python and output the result in Excel
A standard way to develop and distribute packages in Python
A story that makes it easy to estimate the living area using Elasticsearch and Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
Determine the date and time format in Python and convert to Unixtime
How to display bytes in the same way in Java and Python
Easy way to use Wikipedia in Python
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
How to get the date and time difference in seconds with python
What is the fastest way to create a reverse dictionary in python?
How to stop a program in python until a specific date and time
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
I made a POST script to create an issue on Github and register it in the Project
[Python] How to save the installed package and install it in a new environment at once Mac environment
How to input a character string in Python and output it as it is or in the opposite direction.
An easy way to call Java from Python
To represent date, time, time, and seconds in Python
[Python] Concatenate a List containing numbers and write it to an output file.
A complete guidebook to using pyenv, pip and python in an offline environment
How to generate a QR code and barcode in Python and read it normally or in real time with OpenCV
How to save the feature point information of an image in a file and use it for matching
An engineer who has noticed the emo of cryptography is trying to implement it in Python and defeat it
Convert timezoned date and time to Unixtime in Python2.7
Easy way to check the source of Python modules
An easy way to measure the processing speed of a disk recognized by Linux
A Python script that crawls RSS in Azure Status and posts it to Hipchat
How to execute a schedule by specifying the Python time zone and execution frequency
Created a Python library to write complex comprehensions and reduce in an easy-to-read manner
The result of making a map album of Italy honeymoon in Python and sharing it
An easy way to pad the number with zeros depending on the number of digits [Python]
[Selenium] Open the link in a new tab and move it [Python / Chrome Driver]
How to unit test a function containing the current time using freezegun in python
I want to replace the variables in the python template file and mass-produce it in another file.
A note that runs an external program in Python and parses the resulting line
Even beginners can do it! An easy way to write a Sankey Diagram on Plotly
Try to make it using GUI and PyQt in Python
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
Temporarily save a Python object and reuse it in another Python
How to swap elements in an array in Python, and how to reverse an array.
Check the argument type annotation when executing a function in Python and make an error
How to use the __call__ method in a Python class
Probably the easiest way to create a pdf with Python3
How to start the PC at a fixed time every morning and execute the python program
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
A simple way to avoid multiple for loops in Python
Tips for coding short and easy to read in Python
[Super easy! ] How to display the contents of dictionaries and lists including Japanese in Python
I tried to illustrate the time and time in C language
I want to improve efficiency with Python even in an experimental system (2) RS232C and pySerial
Build a Python environment and transfer data to the server
Seeking a unified way to wait and get for state changes in Selenium for Python elements
How to get the last (last) value in a list in Python
Get the current date and time in Python, considering the time difference
I also tried to imitate the function monad and State monad with a generator in Python
I converted the time to an integer, factored it into prime factors, and made a bot to tweet the result (xkcd material)
Introducing a good way to manage DB connections in Python
A python beginner tried to intern at an IT company
Just try to receive a webhook in ngrok and python
PyArmor ~ Easy way to encrypt and deliver python source code ~