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
Selected Reading
How to measure elapsed time in python?
To measure time elapsed during program execution, Python provides several methods. The most common approaches are using time.time(), time.perf_counter(), or the timeit module for benchmarking purposes.
Using time.time()
The simplest method uses time.time() to capture timestamps before and after code execution ?
import time
t0 = time.time()
print("Hello")
time.sleep(0.001) # Simulate some work
t1 = time.time() - t0
print("Time elapsed:", t1, "seconds")
Hello Time elapsed: 0.0015020370483398438 seconds
Using time.perf_counter() (Recommended)
For more precise measurements, use time.perf_counter() which provides the highest available resolution ?
import time
t0 = time.perf_counter()
# Simulate some computation
result = sum(i**2 for i in range(1000))
t1 = time.perf_counter() - t0
print(f"Computation result: {result}")
print(f"Time elapsed: {t1:.6f} seconds")
Computation result: 332833500 Time elapsed: 0.000123 seconds
Using timeit for Benchmarking
For statistical analysis and benchmarking code snippets, use the timeit module which runs code multiple times ?
import timeit
def square_function(x):
return x * x
# Time a code snippet multiple times
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("Best time:", min(execution_times))
Execution times: [0.0234567, 0.0245678, 0.0239876] Best time: 0.0234567
Comparison of Methods
| Method | Precision | Best For |
|---|---|---|
time.time() |
Good | Simple timing tasks |
time.perf_counter() |
High | Performance measurement |
timeit |
Statistical | Benchmarking small code snippets |
Conclusion
Use time.perf_counter() for accurate elapsed time measurement and timeit for benchmarking code performance. Avoid the deprecated time.clock() function in modern Python versions.
Advertisements
