Provided Python code uses the NumPy library to calculate the factorial of integers ranging from 1 to 150. It employs the timeit module to measure the execution time for each factorial computation and stores the results in a list named time_values. The code then utilizes Matplotlib to create a plot, depicting the relationship between the input integer (n) and the corresponding time taken for factorial calculation. The x-axis represents the values of n, while the y-axis represents the time taken in seconds. The resulting plot visualizes the time complexity of the factorial computation as the input size increases.
import numpy as np import time import matplotlib.pyplot as plt import timeit n_values = np.arange(1, 151) time_values = [timeit.timeit(lambda: np.math.factorial(i), number=1) for i in n_values] plt.plot(n_values, time_values) plt.xlabel('n (Factorial of n)') plt.ylabel('Time (seconds)') plt.title('Time to Calculate Factorial of n') plt.show()
Or if you want to just record the time for any function then you can implement below code
import time # Record the start time start_time = time.time() # Your code or function to measure execution time # ... # Record the end time end_time = time.time() # Calculate and print the elapsed time elapsed_time = end_time - start_time print(f"Elapsed Time: {elapsed_time} seconds")