Joel Oh
Joel Oh

Reputation: 35

how do you repeat a whole python script n times to time the whole process?

I am just trying to compare the run time between MATLAB and Python

in Matlab I am just using for example;

tic

for iteration = 1:10

(my codes here)

end

toc

to run a Matlab script 10 times and get the whole time it took to run it 10times and this seems to work fine for my needs.

however I don't know how to do it for Python and for all I've searched on google it doesn't seem to be as simple as compared to Matlab.

please have a quick look at my python codes

from funcFile import *
from stl import mesh 
import time

start = time.time

(and my python codes here)

end = time.time()
print(end-start)

so this basically runs the codes and also gives out the time it took to run, but I also want to repeat it about 10times to know how much time it took to run 10 times.

which function should I be using?

Upvotes: 1

Views: 87

Answers (2)

M Omer Sharif Bhatti
M Omer Sharif Bhatti

Reputation: 132

Its really simple enclose your code in for loop. Hope you get the Answer :)

from datetime import datetime

start = datetime.now()

for iteration in range(10):
    print("Your Code Here Remember the indentation")
    
end = datetime.now()
difference = end-start

print(f"Executed in {difference.microseconds/1000.0} Seconds")

Upvotes: 1

AKX
AKX

Reputation: 168913

The simplest way is

import time

for x in range(10):
   start = time.time()
   # (and my python codes here)
   end = time.time()
   print(end - start)

but I'd recommend refactoring your (python codes) into a function you call:

import time

def my_code():
   # (and my python codes here)


def run_n_times(func, n):
   for x in range(n):
      start = time.time()
      func()
      end = time.time()
      print(end - start)

run_n_times(my_code, 10)

If you want to be even fancier, you can use the timeit module.

Upvotes: 2

Related Questions