10

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
Mus
  • 7,290
  • 24
  • 86
  • 130
Niel Agneessens
  • 149
  • 1
  • 2
  • 8
  • use a shell command to time the execution (Unix `time`), for python use the `timeit` module – rioV8 Aug 08 '19 at 09:35

4 Answers4

9

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))
Maeaex1
  • 703
  • 7
  • 36
4

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.

Axois
  • 1,961
  • 2
  • 11
  • 22
2

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
vahvero
  • 525
  • 11
  • 24
1

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)
Abhishek Sharma
  • 1,909
  • 2
  • 15
  • 24