Python uses 3.6.0.
At stop_watch.py
print(f"{func.__name__}Is{elapsed_time}It took a second")
However, this notation does not work unless it is 3.6.0 or higher. Please rewrite as appropriate according to your version. The other parts are unconfirmed, but I think it will work with 3x.
To measure time with Python, basically use the method in the following article.
[Python] Measure and display the time required for processing python> Processing time measurement> time.time () --start_time Function that measures the processing time of a method with python
You can also measure the time with the above method. However, the logic you want to write and the time measurement are combined.
Therefore, there is a clever way to completely separate logic and time measurement, so I will share it.
stop_watch.py
from functools import wraps
import time
def stop_watch(func) :
@wraps(func)
def wrapper(*args, **kargs) :
start = time.time()
result = func(*args,**kargs)
elapsed_time = time.time() - start
print(f"{func.__name__}Is{elapsed_time}It took a second")
return result
return wrapper
The above code is the process to measure the time.
This code uses a decorator.
The actual processing is stored in func
, the measurement start time is stored in start
, and the time taken for processing is stored in ʻelaspsed_time`.
If you would like to know more about decorators, please read this article in detail.
12 Steps to Understanding Python Decorators
test.py
from stop_watch import stop_watch
@stop_watch
def func() :
j=0
for i in range(99999999) :
j+=i
print(j)
func()
The actual usage is like this.
Just write @stop_watch
above the function you want to measure the time.
(* It is assumed that the above stop_watch.py
and the following test.py
are in the same directory (folder). If they are different, please rewrite the import process as appropriate)
Result is,
result
4999999850000001
func is 6.330682277679443 It took 2 seconds
Is displayed. The result of the function whose time you want to measure is displayed on the first line. On the second line, the name of the function for which you want to measure the time and the time taken to execute that function are displayed.
It has nothing to do with logic, but if you want to see some results, the decorator will shine. This time, it was a task of measuring time. I hope it helps something.
Recommended Posts