Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the timing Execution Speed of Python Code?
Measuring the execution time of Python code is essential for performance optimization and benchmarking. Python provides several built-in modules like time and timeit to accurately measure code execution speed.
Using time Module
The time.perf_counter() function provides the highest available resolution and is recommended for measuring short durations ?
import time
t0 = time.perf_counter()
print("Hello")
t1 = time.perf_counter()
print("Time elapsed:", t1 - t0, "seconds")
Hello Time elapsed: 2.7499999851558823e-05 seconds
Using time.time()
For wall-clock time measurement, you can use time.time() ?
import time
start = time.time()
# Simulate some work
sum(range(1000000))
end = time.time()
print(f"Execution time: {end - start:.6f} seconds")
Execution time: 0.021547 seconds
Using timeit Module
The timeit module provides more accurate measurements by running code multiple times and calculating statistical data ?
import timeit
def square_function(x):
return x * x
# Measure execution time
execution_times = timeit.repeat("for x in range(100): square_function(x)",
"from __main__ import square_function",
number=10000, repeat=3)
print("Execution times:", execution_times)
print(f"Best time: {min(execution_times):.6f} seconds")
Execution times: [0.051234, 0.052891, 0.051456] Best time: 0.051234 seconds
Using timeit.timeit() for Single Measurement
import timeit
# Time a simple expression
time_taken = timeit.timeit('sum(range(100))', number=10000)
print(f"Time for sum(range(100)): {time_taken:.6f} seconds")
Time for sum(range(100)): 0.034567 seconds
Comparison of Methods
| Method | Best For | Accuracy | Use Case |
|---|---|---|---|
time.perf_counter() |
Short durations | High | Single measurements |
time.time() |
Wall-clock time | Medium | General timing |
timeit |
Benchmarking | Highest | Statistical analysis |
Conclusion
Use timeit for accurate benchmarking and statistical analysis. For simple timing measurements, time.perf_counter() provides high-resolution timing suitable for most performance monitoring needs.
