๐Python Timer Function: Measure Elapsed Time with Examples
Python Timer Function: Python’s time module provides efficient tools to manage and measure time-related operations. This module includes various functions for tracking performance, computing elapsed time, and handling date-time objects.
๐Key Python Timer Functions
- time.time() โ Tracks elapsed time in seconds.
- time.sleep() โ Pauses code execution for a specified time.
- time.ctime() โ Converts timestamps to readable string format.
- time.gmtime() โ Displays structured time in UTC format.
- time.process_time() โ Tracks CPU processing time for precise performance evaluation.
- time.thread_time() โ Measures active thread execution time.
๐How to Use Python’s time.time() for Elapsed Time
The time.time() function records the current time in seconds since the Unix epoch (January 1, 1970).
๐Python Timer Function Example Code:
python
import time
start_time = time.time()
print(“Starting timer…”)
time.sleep(2) # Pause for 2 seconds
end_time = time.time()
elapsed_time = end_time – start_time
print(f”Elapsed time: {elapsed_time} seconds”)
๐Output:
css
Starting timer…
Elapsed time: 2.001 seconds
๐Using time.sleep() to Delay Code Execution
The time.sleep() function pauses your program for the specified number of seconds.
๐Example Code:
python
import time
print(“Starting delay…”)
time.sleep(3)
print(“Delay completed!”)
๐Output:
arduino
Starting delay…
Delay completed!
๐Converting Time to Readable Format with time.ctime()
The time.ctime() function converts timestamps into a human-readable string.
๐Example Code:
python
import time
current_time = time.time()
print(“Current time in human-readable format:”, time.ctime(current_time))
๐Output:
pgsql
Current time in human-readable format: Mon Mar 14 10:30:05 2025
๐Tracking CPU Time with time.process_time()
The time.process_time() function is ideal for performance benchmarking.
๐Example Code:
python
from time import process_time
start_time = process_time()
for i in range(1000000):
pass
end_time = process_time()
print(“CPU process time:”, end_time – start_time)
๐Output:
arduino
CPU process time: 0.025 seconds
๐Measuring Thread Execution with time.thread_time()
This function tracks the time spent specifically on active thread execution.
๐Example Code:
python
import time
import threading
def sample_task():
start_time = time.thread_time()
for _ in range(10000000):
pass
end_time = time.thread_time()
print(f”Thread execution time: {end_time – start_time}”)
thread = threading.Thread(target=sample_task)
thread.start()
thread.join()
๐Output:
css
Thread execution time: 1.03 seconds
