Python: Measure execution time
Method Execution Time
Write a Python program to get the execution time of a Python method.
Sample Solution:
Python Code:
Sample Output:
Time to sum of 1 to 5 and required time to calculate is : (15, 2.384185791015625e-06)
Explanation:
The above Python code defines a function sum_of_n_numbers() that calculates the sum of the first n positive integers, and returns the sum and the time it took to calculate the sum.
time module - This module provides various time-related functions.
The sum_of_n_numbers() function uses a for loop to add up the first n positive integers and calculates the time it takes to do so using the time.time() function to get the start and end times of the operation. The function returns a tuple containing the sum of the first n positive integers and the time taken to calculate the sum.
Finally the code then calls the sum_of_n_numbers() function with an argument of n=5, and prints the result to the console using the print() function. The output displays the time it took to calculate the sum of the first 5 positive integers and the calculated sum.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Python program to measure the execution time of a function using both `time` and `timeit` modules.
- Write a Python program to compare the execution times of iterative and recursive implementations of factorial computation.
- Write a Python program to calculate the execution time of a loop running for a million iterations.
- Write a Python program to measure the execution time of reading a large file line by line.
Go to:
Previous: Write a Python program to get height and the width of console window.
Next: Write a Python program to sum of the first n positive integers.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.