Measuring Execution Time of a Code Snippet

Write a Python program that uses the time module to measure how long a piece of code takes to execute.

Example 1:

Input: 
def code_to_test():
    return sum([i for i in range(1000000)])
Output: 0.05485248565673828  # Output may vary

Example 2:

Input: 
def code_to_test():
    return "".join([str(i) for i in range(10000)])
Output: 0.002991914749145508  # Output may vary

The time module contains a function time() that returns the current system time in seconds since the epoch (January 1, 1970). You can use this function to calculate the execution time of a piece of code.

import time

def measure_execution_time(code_to_test):
    start_time = time.time()
    code_to_test()
    end_time = time.time()

    return end_time - start_time

# Test the function
def code_to_test_1():
    return sum([i for i in range(1000000)])

def code_to_test_2():
    return "".join([str(i) for i in range(10000)])

print(measure_execution_time(code_to_test_1))  # Output may vary
print(measure_execution_time(code_to_test_2))  # Output may vary

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!