Python Timer and Time Measurement (time module)
Page Info
Content
Python Timer and Time Measurement (time module)
In Python, the time
module allows you to measure execution time, create delays, and work with timestamps. It is commonly used for performance testing and benchmarking code.
Measuring Execution Time
import time
# Record start time
start_time = time.time()
# Code block to measure
total = 0
for i in range(1, 1000000):
total += i
# Record end time
end_time = time.time()
# Calculate elapsed time
print(f"Elapsed time: {end_time - start_time:.4f} seconds")
Explanation:
time.time()
: Returns the current time in seconds since the epoch (floating point).- Subtract start time from end time to get elapsed time.
Using time.sleep() to Pause Execution
import time
print("Start")
time.sleep(3) # Pause execution for 3 seconds
print("End after 3 seconds")
Explanation:
time.sleep(seconds)
: Delays program execution for the specified number of seconds.- Useful for creating pauses or simulating delays in programs.
Using time.perf_counter() for High-Precision Timing
import time
start = time.perf_counter()
# Code block to measure
sum_value = sum(range(1, 1000000))
end = time.perf_counter()
print(f"High-precision elapsed time: {end - start:.6f} seconds")
Explanation:
time.perf_counter()
provides a high-resolution timer for more precise measurement.- Ideal for benchmarking small code blocks or performance-critical operations.
Key Points
- time.time(): Measures wall-clock time in seconds.
- time.sleep(): Pauses execution for a given time.
- time.perf_counter(): High-resolution timer for accurate measurements.
- Useful for profiling code, performance testing, and adding delays in Python programs.
SEO Keywords
Python timer example, Python measure execution time, Python time module, Python time.sleep, Python perf_counter, Python benchmarking code
Using Python's time module, you can efficiently measure the execution duration of code blocks, pause program execution, and perform high-precision benchmarking.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.