I use it a lot but forget it so I output it to remember I intend to write it easily for beginners
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
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?
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