Middle
How do you determine the speed of a program?
sobes.tech AI
Answer from AI
Using the timeit module for precise measurement of execution time of small code snippets or functions.
import timeit
def my_function():
# Your code to measure
pass
# Measuring execution time of my_function
execution_time = timeit.timeit(stmt=my_function, number=1000) # Run 1000 times and measure total time
print(f"Execution time: {execution_time} seconds")
You can also use the time module for simpler measurements.
import time
start_time = time.time() # Start measurement
# Your code to measure
time.sleep(1) # Example work
end_time = time.time() # End measurement
print(f"Execution time: {end_time - start_time} seconds")
For profiling and identifying bottlenecks in more complex programs, modules cProfile and profile are used.
import cProfile
def slow_function():
for _ in range(100000):
pass
cProfile.run('slow_function()') # Profile the function call
Another way is to use a decorator to measure function execution time.
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds")
return result
return wrapper
@timer_decorator
def fast_function():
time.sleep(0.1)
fast_function()