How to check the execution time of Python script

Published on Aug. 22, 2023, 12:15 p.m.

To check the execution time of a Python script, there are several approaches that you can take:

  1. Using the time module: You can use the time module to record the start and end time of the script and then calculate the difference between the two times. Here’s an example:
import time

start_time = time.time()

# Your Python code here

end_time = time.time()
print(f"Execution time: {end_time - start_time:.5f} seconds")

This will print the execution time of your code in seconds (with 5 decimal places).
2. Using the timeit module: The timeit module provides a simple way to time small bits of Python code. You can use it to time your script like this:

import timeit

def main():
   # Your Python code here

print(f"Execution time: {timeit.timeit(main, number=1)} seconds")

This will print the execution time of your code in seconds.
3. Using a decorator: You can create a decorator that calculates the execution time of a function. Here’s an example:

import time

def timing_decorator(func):
   def wrapper(*args, **kwargs):
       start_time = time.time()
       result = func(*args, **kwargs)
       end_time = time.time()
       print(f"Execution time: {end_time - start_time:.5f} seconds")
       return result

   return wrapper

@timing_decorator
def main():
   # Your Python code here

This will print the execution time of your code in seconds and also return the result of the function.

Tags:

related content