Code Explanation:
Importing Required Module
import timeit
This imports the timeit module, which is specifically used to measure the execution time of small bits of Python code with high accuracy.
Defining the Test Function
def test_function():
return sum(range(100))
Defines a simple function that computes the sum of integers from 0 to 99.
This is the function whose execution time we want to benchmark.
Preparing the Statement to Time
stmt = "test_function()"
This is the string of code that timeit will execute.
It must be a string, not a direct function call.
Setting Up the Environment
setup = globals()
globals() provides the global namespace so timeit can access test_function.
Without this, timeit would not know what test_function is and would raise a NameError.
Measuring Execution Time
print(timeit.timeit(stmt, globals=setup, number=1000))
timeit.timeit(...) runs the stmt 1,000 times (number=1000) and returns the total time taken in seconds.
print(...) then outputs this time.
Output
The printed result will be a float (e.g., 0.0054321), representing how many seconds it took to run test_function() 1,000 times.
This value gives you a rough sense of the performance of the function.
Final Output:
A: 0.0025
.png)

0 Comments:
Post a Comment