Middle
How can you evaluate how fast an algorithm works?
sobes.tech AI
Answer from AI
There are several ways to evaluate the speed of an algorithm:
-
Analysis of time complexity (Big O) — a theoretical estimate showing how the execution time of an algorithm grows with increasing input size.
-
Profiling and timing — practical assessment using tools and timing functions.
Example in Python using the time module to measure function execution time:
import time
def example_algorithm(n):
total = 0
for i in range(n):
total += i
return total
start_time = time.time()
example_algorithm(10**6)
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
-
Profilers — such as
cProfilefor Python, which allow detailed analysis of which parts of the code take the most time. -
Testing on different input sizes — helps understand how the algorithm scales.
Thus, combining theoretical analysis and practical measurement provides a comprehensive understanding of the algorithm's performance.