How to Measure Elapsed Time in Python?

Summary: You can evaluate the execution time of your code by saving the timestamps using time.time() at the beginning and the end of your code. Then, you can find the difference between the start and the end timestamps that results in the total execution time.


[toc]

Problem: Given a Python program; how will you measure the elapsed time ( the time taken by the code to complete execution)?

Consider the following snippet:

import time


def perimeter(x):
    time.sleep(5)
    return 4 * x


def area(x):
    time.sleep(2)
    return x * x


p = perimeter(8)
print("Perimeter: ", p)
a = area(8)
print("Area: ", a)
  • Challenges:
    • How will you find the time taken by each function in the above program to execute?
    • How will you compute the total time elapsed by the entire code?

Tidbit: sleep() is a built-in method of the time module in Python that is used to delay the execution of your code by the number of seconds specified by you.

Now, let us conquer the given problem and dive into the solutions.

Method 1: Using time.time()

time.time() is a function of the time module in Python that is used to get the time in seconds since the epoch. It returns the output, i.e., the time elapsed, as a floating-point value.

The code:

import time


def perimeter(x):
    time.sleep(5)
    return 4 * x


def area(x):
    time.sleep(2)
    return x * x


begin = time.time()

start = time.time()
p = perimeter(8)
end = time.time()
print("Perimeter: ", p)
print("Time Taken by perimeter(): ", end - start)

start = time.time()
a = area(8)
end = time.time()
print("Area: ", a)
print("Time Taken by area(): ", end - start)

end = time.time()
print("Total time elapsed: ", end - begin)

Output:

Perimeter:  32
Time Taken by Perimeter():  5.0040647983551025
Area:  64
Time Taken by area():  2.0023691654205322
Total time elapsed:  7.006433963775635

Approach:
➀ Keep track of the time taken by each function by saving the time stamp at the beginning of each function with the help of a start variable and using the time() method.
➀ Similarly, the end time, i.e., the timestamp at which a function completes its execution, is also tracked with the help of the time() function at the end of each function.
➀ Finally, the difference between the end and the start time gives the total time taken by a particular function to execute.
➀ To find the total time taken by the entire program to complete its execution, you can follow a similar approach by saving the time stamp at the beginning of the program and the time stamp at the end of the program and then find their difference.

Discussion: If you are working on Python 3.3 or above, then another option to measure the elapsed time is perf_counter or process_time, depending on the requirements. Prior to Python 3.3, you could have used time.clock, however, it has been currently deprecated and is not recommended.

Method 2: Using time.perf_counter()

In Python, the perf_counter() function from the time module is used to calculate the execution time of a function and gives the most accurate time measure of the system. The function returns the system-wide time and also takes the sleep time into account.

import time


def perimeter(x):
    time.sleep(5)
    return 4 * x


def area(x):
    time.sleep(2)
    return x * x


begin = time.perf_counter()

start = time.perf_counter()
p = perimeter(8)
end = time.perf_counter()
print("Perimeter: ", p)
print("Time Taken by perimeter(): ", end - start)

start = time.perf_counter()
a = area(8)
end = time.perf_counter()
print("Area: ", a)
print("Time Taken by area(): ", end - start)

end = time.perf_counter()
print("Total time elapsed: ", end - begin)

Output:

Perimeter:  32
Time Taken by perimeter():  5.0133558
Area:  64
Time Taken by are():  2.0052768
Total time elapsed:  7.0189293

Caution: The perf_counter() function not only counts the time elapsed along with the sleep time, but it is also affected by other programs running in the background on the system. Hence, you must keep this in mind while using perf_counter for performance measurement. It is recommended that if you utilize the perf_counter() function, ensure that you run it several times so that the average time would give an accurate estimate of the execution time.

Method 3: Using time.process_time()

Another method from the time module used to estimate the execution time of the program is process_time(). The function returns a float value containing the sum of the system and the user CPU time of the program. The major advantage of the process_time() function is that it does not get affected by the other programs running in the background on the machine, and it does not count the sleep time.

import time


def perimeter(x):
    time.sleep(5)
    return 4 * x


def area(x):
    time.sleep(2)
    return x * x


begin = time.process_time()

start = time.process_time()
p = perimeter(8)
end = time.process_time()
print("Perimeter: ", p)
print("Time Taken by perimeter(): ", end - start)

start = time.process_time()
a = area(8)
end = time.process_time()
print("Area: ", a)
print("Time Taken by area(): ", end - start)

end = time.process_time()
print("Total time elapsed: ", end - begin)

Output:

Perimeter:  32
Time Taken by perimeter():  5.141000000000173e-05
Area:  64
Time Taken by area():  4.1780000000005146e-05
Total time elapsed:  0.00029919000000000473

Method 4: Using timeit Module

timeit is a very handy module that allows you to measure the elapsed time of your code. A major advantage of using the timeit module is its ability to measure and execute lambda functions wherein you can specify the number of executions as an argument.

Note: The timeit module turns off the garbage collection process temporarily while calculating the execution time.

Let us dive into the different methods of this module to understand how you can use it to measure execution time within your code.

4.1 Using timeit.timeit()

Example 1: In the following example, we will have a look at a lambda function being executed with the help of the timeit module such that we will be specifying the number of times this anonymous function will be executed and then calculate the time taken to execute it.

import timeit

count = 1


def foo(x):
    global count
    print(f'Output for call{count} = {x * 3}')
    count += 1


a = timeit.timeit(lambda: foo(8), number=3)
print("Time Elapsed: ", a)

Output:

Output for call1 = 24
Output for call2 = 24
Output for call3 = 24
Time Elapsed:  6.140000000000312e-05

Explanation: After importing the timeit module, you can call the lambda function within the timeit.timeit() function as a parameter and also specify the number of times the function will be called with the help of the second parameter, i.e., number. In this case, we are calling the lambda function three times and printing the output generated by the function every time. Finally, we displayed the total time elapsed by the function.

4.2 Using timeit.repeat

Even though the above method allowed us to calculate the execution time of a lambda function, it is not safe to say that the value evaluated by the timeit() function was accurate. To get a more accurate result, you can record multiple values of execution time and then find their mean to get the best possible outcome. This is what timeit.repeat() function allows you to do.

Example:

import timeit

count = 1


def foo(x):
    global count
    print(f'Output for call{count} = {x * 3}')
    count += 1


a = timeit.repeat(lambda: foo(8), number=1, repeat=3)
print(a)
s = 0
for i in a:
    s = s + i
print("Best Outcome: ", s)

Output:

Output for call1 = 24
Output for call2 = 24
Output for call3 = 24
[5.160000000001275e-05, 1.3399999999996748e-05, 1.0399999999993748e-05]
Best Outcome:  7.540000000000324e-05

4.3 Using timeit.default_timer()

Instead of using timeit.timeit() function, we can also use the timeit.default_timer(), which is a better option as it provides the best clock available based on the platform and Python version you are using, thereby generating more accurate results. Using timeit.default_timer() is quite similar to using time.time().

Example:

import timeit
import time


def perimeter(x):
    time.sleep(5)
    return 4 * x


def area(x):
    time.sleep(2)
    return x * x


begin = timeit.default_timer()

start = timeit.default_timer()
p = perimeter(8)
end = timeit.default_timer()
print("Perimeter: ", p)
print("Time Taken by Perimeter(): ", end - start)

start = timeit.default_timer()
a = area(8)
end = timeit.default_timer()
print("Area: ", a)
print("Time Taken by Perimeter(): ", end - start)

end = timeit.default_timer()
print("Total time elapsed: ", end - begin)

Output:

Perimeter:  32
Time Taken by Perimeter():  5.0143883
Area:  64
Time Taken by Perimeter():  2.0116591
Total time elapsed:  7.0264410999999996

Methdo 5: Using datetime.datetime.now()

The elapsed time can also be calculated using the DateTime.datetime.now() function from the datetime module in Python. The output of the method is represented as days, hours, and minutes. However, the disadvantage of this method is that it is slower than the timeit() module since calculating the difference in time is also included in the execution time.

Example:

import datetime
import time


def perimeter(x):
    time.sleep(5)
    return 4 * x


def area(x):
    time.sleep(2)
    return x * x


begin = datetime.datetime.now()

start = datetime.datetime.now()
p = perimeter(8)
end = datetime.datetime.now()
print("Perimeter: ", p)
print("Time Taken by Perimeter(): ", end - start)

start = datetime.datetime.now()
a = area(8)
end = datetime.datetime.now()
print("Area: ", a)
print("Time Taken by Perimeter(): ", end - start)

end = datetime.datetime.now()
print("Total time elapsed: ", end - begin)

Output:

Perimeter:  32
Time Taken by Perimeter():  0:00:05.003221
Area:  64
Time Taken by Perimeter():  0:00:02.011262
Total time elapsed:  0:00:07.014483

Conclusion

Thus to sum things up, you can use one of the following modules in Python to calculate the elapsed time of your code:

  • The time module
  • The timeit module
  • The datetime module

With that, we come to the end of this tutorial, and I hope you found it helpful. Please subscribe and stay tuned for more interesting articles.

Here’s a list of highly recommended tutorials if you want to dive deep into the execution time of your code and much more: