Python Calculate Execution Time of a Program

To calculate the execution time of a Python program, you can use one of these methods:

The time() function from the time module which returns the current system time. You can call it before and after your code and subtract them to get the elapsed time.

The clock() function from the time module which returns the CPU execution time. You can use it similarly to time().

The datetime.now() function from the datetime module which returns the current date and time. You can use it similarly to time().

The perf_counter() function from the time module which returns a high-resolution performance counter. You can use it similarly to time().

The timeit() function from the timeit module which measures the execution time of small code snippets by running them multiple times.

Here is an example of using each method to measure the execution time of a simple loop:

import time
import datetime
import timeit

# Using time()
start = time.time()
for i in range(1000000):
  pass
end = time.time()
print(f"Elapsed time using time(): {end - start} seconds")


# Using clock()

start = time.clock()
for i in range(1000000):
  pass
end = time.clock()
print(f"Elapsed time using clock(): {end - start} seconds")


# Using datetime.now()

start = datetime.datetime.now()
for i in range(1000000):
  pass
end = datetime.datetime.now()
print(f"Elapsed time using datetime.now(): {end - start}")


# Using perf_counter()

start = time.perf_counter()
for i in range(1000000):
  pass
end = time.perf_counter()
print(f"Elapsed time using perf_counter(): {end - start} seconds")


# Using timeit()
elapsed = timeit.timeit("for i in range(1000000): pass", number=1)
print(f"Elapsed time using tiemit(): {elapsed} seconds")

The output of each method may vary depending on your system and environment, but here is a possible output:

Elapsed time using tiemit(): 0.03299999999999997 seconds
Elapsed tiemit() using clock(): 0.03125 seconds
Elapsed tiemit() using datetime.now(): 0:00:00.031250
Elapsed tiemit() using perf_counter(): 0.03124999999999858 seconds
Elapsed tiemit() using tiemit(): 0.03125 seconds

It is a major task in Machine learning. It is important to know the time taken by your code or function to run so that you can improve it later with some tricks.

# The Simplest Way
import time
start_time = time.time()
...
func()
...
end_time = time.time()
print("Execution Time: ",(end_time-start_time))

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions