Is there a way to see how long a script took to execute/complete in VS Code?
I'm looking for a message like:
Program finished in 30ms
Is there a way to see how long a script took to execute/complete in VS Code?
I'm looking for a message like:
Program finished in 30ms
Use 'time'
When your script starts:
import time
start_time = time.time()
do something # here your actual code/routine
print("Process finished --- %s seconds ---" % (time.time() - start_time))
You can create a simple decorator function to time your functions.
import time
def decoratortimer(decimal):
def decoratorfunction(f):
def wrap(*args, **kwargs):
time1 = time.monotonic()
result = f(*args, **kwargs)
time2 = time.monotonic()
print('{:s} function took {:.{}f} ms'.format(f.__name__, ((time2-time1)*1000.0), decimal ))
return result
return wrap
return decoratorfunction
@decoratortimer(2)
def callablefunction(name):
print(name)
print(callablefunction('John'))
I suggest using time.monotonic
(which is a clock that doesnt go backwards) to increase the accuracy.
Easiest way to achieve this is by purely coding the time to program. perf_counter
offers highest accuracy from the time
functions.
from time import perf_counter, sleep
def main():
sleep(5)
start_time = perf_counter()
main() # Function to measure
passed_time = perf_counter() - start_time
print(f"It took {passed_time}") # It took 5.007398507999824
For finding your function run time prefer time.perf_counter() over time.time(). See the below link for details
Understanding time.perf_counter() and time.process_time()
You can create your own custom timer using something like this
from time import perf_counter
def f(a1,a2):
return a1 * a2
def timer(f,*args):
start = perf_counter()
f(*args)
return (1000 * (perf_counter()-start)) # this returns time in ms
a1 = np.random.rand(100)
a2 = np.random.rand(100)
np.mean([timer(f,a1,a2) for _ in range(100)]) # average out result for 100 runs
If you are using jupyter notebook use the following
%%timeit
f(a1,a2)