
👉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