Measuring the execution time in python.

Measuring the execution time of your python code snippets using an in-built python library timeit.

timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1,000,000)

  • stmt - the code for which you want to measure the execution time.
  • setup - setup details that need to be executed before stmt.
  • timer - output timer value, timeit() already has a default value set.
  • number - the sample size.  The default value is 1000000.
import timeit

def reverse_string1(s):
   return s[::-1]


def reverse_string2(s):
   return "".join(reversed(s))

def main():
   s = "abcd"
   time = timeit.repeat(lambda: reverse_string1(s))
   print("reverse_string1 time - ", time)
   time = timeit.repeat(lambda: reverse_string2(s))
   print("reverse_string2 time - ", time)

Output:

reverse_string1 time -  [0.2474247, 0.24140289999999998, 0.23561960000000004, 0.2515652999999999, 0.23337079999999988]
reverse_string2 time -  [0.48499369999999997, 0.4952494999999999, 0.5008286000000002, 0.5879252999999998, 0.5180828000000002]

You can see the method of s[::-1] faster than "".join(reversed(s).