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 write a function to get the time spent in each function in Python?
In Python, measuring the execution time of functions is essential for performance analysis and optimization. Python provides several built-in modules like time and datetime to measure function execution time effectively.
- Using time.time() Method
- Using time.process_time() Function
- Using datetime.now() Function
- Creating a Timer Decorator Function
Using time.time() Method
The time.time() method returns the current time in seconds since January 1, 1970 (Unix epoch). This method measures wall-clock time, including time spent waiting for I/O operations or system delays.
To measure execution time, record the time before and after function execution, then calculate the difference.
Example
The following program measures execution time using time.time() ?
import time
def sample_function():
"""A sample function that performs some computation"""
total = 0
for i in range(1000000):
total += i
return total
# Record start time
start_time = time.time()
# Execute the function
result = sample_function()
print(f"Result: {result}")
# Record end time
end_time = time.time()
# Calculate execution time
execution_time = end_time - start_time
print(f"Execution time: {execution_time:.6f} seconds")
Result: 499999500000 Execution time: 0.045231 seconds
Using time.process_time() Function
The time.process_time() function measures CPU execution time only, excluding sleep time or time spent waiting for I/O operations. This is more accurate for measuring actual computation time.
Example
The following program calculates CPU time to find the maximum element in a list ?
import time
def find_maximum(numbers):
"""Function to find maximum element"""
return max(numbers)
# Record CPU start time
start_time = time.process_time()
# Execute function
input_list = [2, 5, 9, 1, 6, 15, 3, 8, 12]
max_element = find_maximum(input_list)
print(f"Maximum element: {max_element}")
# Record CPU end time
end_time = time.process_time()
# Calculate CPU execution time
cpu_time = end_time - start_time
print(f"CPU execution time: {cpu_time:.8f} seconds")
Maximum element: 15 CPU execution time: 0.00000120 seconds
Using datetime.now() Function
The datetime.now() function returns the current local time with microsecond precision. When subtracting datetime objects, it returns a timedelta object representing the time difference.
Example
The following program measures execution time using datetime.now() ?
from datetime import datetime
def count_words(text):
"""Function to count words in text"""
return len(text.split())
# Record start time
start_time = datetime.now()
# Execute function
sample_text = "Python programming is fun and powerful for data analysis"
word_count = count_words(sample_text)
print(f"Number of words: {word_count}")
# Record end time
end_time = datetime.now()
# Calculate execution time
execution_time = end_time - start_time
print(f"Execution time: {execution_time}")
print(f"Execution time (seconds): {execution_time.total_seconds():.6f}")
Number of words: 10 Execution time: 0:00:00.000156 Execution time (seconds): 0.000156
Creating a Timer Decorator Function
For measuring multiple functions consistently, create a decorator that automatically times any function ?
import time
from functools import wraps
def timer_decorator(func):
"""Decorator to measure function execution time"""
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
print(f"{func.__name__} executed in {execution_time:.6f} seconds")
return result
return wrapper
@timer_decorator
def fibonacci(n):
"""Calculate fibonacci number"""
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
@timer_decorator
def factorial(n):
"""Calculate factorial"""
if n <= 1:
return 1
return n * factorial(n-1)
# Test the decorated functions
print(f"Fibonacci(10): {fibonacci(10)}")
print(f"Factorial(5): {factorial(5)}")
fibonacci executed in 0.000067 seconds fibonacci executed in 0.000013 seconds fibonacci executed in 0.000011 seconds fibonacci executed in 0.000009 seconds fibonacci executed in 0.000008 seconds fibonacci executed in 0.000008 seconds fibonacci executed in 0.000007 seconds fibonacci executed in 0.000007 seconds fibonacci executed in 0.000007 seconds fibonacci executed in 0.000007 seconds fibonacci executed in 0.000007 seconds Fibonacci(10): 55 factorial executed in 0.000008 seconds factorial executed in 0.000006 seconds factorial executed in 0.000006 seconds factorial executed in 0.000005 seconds factorial executed in 0.000005 seconds Factorial(5): 120
Comparison of Methods
| Method | Measures | Best For | Precision |
|---|---|---|---|
time.time() |
Wall-clock time | Overall execution time | Microseconds |
time.process_time() |
CPU time only | Pure computation time | Nanoseconds |
datetime.now() |
Wall-clock time | Human-readable format | Microseconds |
| Decorator | Wall-clock time | Multiple functions | Microseconds |
Conclusion
Use time.process_time() for measuring pure computation time, time.time() for overall execution time including I/O, and decorators for consistent timing across multiple functions. Choose the method based on whether you need CPU-only time or total elapsed time.
