Skip to content

Commit

Permalink
⚡✨ feat(utils): Add ormat_elapsed_time Utility for Human-Readable Tim…
Browse files Browse the repository at this point in the history
…e Formatting

#### Key Features:
- Handles time durations less than a minute by returning only seconds.
- For durations of one minute or more, returns the time in the format of 'X minute(s) and Y second(s)'.
- Provides a clean and formatted output, ensuring clarity in time representation.

This utility is useful for improving the readability of elapsed time in logging and performance measurement contexts.
  • Loading branch information
MEHRSHAD-MIRSHEKARY committed Oct 4, 2024
1 parent 6367c51 commit 055424a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
8 changes: 4 additions & 4 deletions django_logging/decorators/execution_tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
import os
import time
from functools import wraps
from typing import Callable, Optional
from typing import Any, Callable, Optional

from django.conf import settings
from django.db import connection

from django_logging.utils.time import format_elapsed_time
from django_logging.validators.config_validators import (
validate_boolean_setting,
validate_integer_setting,
Expand Down Expand Up @@ -69,7 +70,7 @@ def execution_tracker(

def decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
def wrapper(*args: Any, **kwargs: Any) -> Any:
start_time = time.time()

# Check if DEBUG is True and log_queries is enabled; if not, ignore query tracking
Expand All @@ -82,15 +83,14 @@ def wrapper(*args, **kwargs):

# Calculate execution time
elapsed_time = time.time() - start_time
minutes, seconds = divmod(elapsed_time, 60)

# Get detailed function information
module_name = func.__module__
function_name = func.__qualname__
file_path = os.path.abspath(func.__code__.co_filename)
line_number = func.__code__.co_firstlineno

time_message = f"{minutes} minute(s) and {seconds:.4f} second(s)"
time_message = format_elapsed_time(elapsed_time)
log_message = (
f"Performance Metrics for Function: '{function_name}'\n"
f" Module: {module_name}\n"
Expand Down
18 changes: 18 additions & 0 deletions django_logging/utils/time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def format_elapsed_time(elapsed_time: float) -> str:
"""Formats the elapsed time into a human-readable string.
If the time is less than a minute, returns only seconds. Otherwise,
returns the time in minutes and seconds.
Args:
elapsed_time: Time in seconds as a float.
Returns:
A string representing the formatted time.
"""
minutes, seconds = divmod(elapsed_time, 60)

if minutes > 0:
return f"{int(minutes)} minute(s) and {seconds:.2f} second(s)"
return f"{seconds:.2f} second(s)"

0 comments on commit 055424a

Please sign in to comment.