Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/Write a decorator function to log the execution time of a function.

Write a decorator function to log the execution time of a function.

Python/Codingeasy2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-08-08

To log the execution time of a function, you can create a Python decorator that wraps the target function, records the time before and after its execution, and then logs the duration. This pattern is…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
American Express

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like American Express. While less common, it tests deeper understanding that distinguishes strong candidates.

How to Approach This

Start by clearly defining the core concept being asked about. Interviewers want to see that you understand the fundamentals before diving into implementation details. Structure your answer with a definition, then explain the practical application with a concise example. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
380 wordsIncludes code

To log the execution time of a function, you can create a Python decorator that wraps the target function, records the time before and after its execution, and then logs the duration. This pattern is invaluable for performance monitoring and debugging in data pipelines.

Mechanics and Why

A decorator is a higher-order function that takes another function as an argument and extends or modifies its behavior without explicitly changing its source code. The core steps involve:

  • Wrapping the Function: Define an inner wrapper function that will execute the original function.
  • Timing: Use time.perf_counter() for high-resolution, process-specific timing, ideal for measuring short durations accurately. Avoid time.time() which is system-wide and less precise for this use case.
  • Logging: Capture the start and end times, calculate the difference, and log it. For production systems, leverage Python's logging module instead of print for better control over log levels, destinations, and structured output.
  • Preserving Metadata: Crucially, functools.wraps copies important metadata (like __name__, __doc__) from the original function to the wrapper, ensuring introspection and debugging tools work as expected.
  • import time
    import functools
    import logging
    

    # Configure basic logging for demonstration
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

    def log_execution_time(func):
    @functools.wraps(func)
    def wrapper(args, *kwargs):
    start_time = time.perf_counter()
    result = func(args, *kwargs)
    end_time = time.perf_counter()
    duration = end_time - start_time
    logging.info(f"Function '{func.__name__}' executed in {duration:.4f} seconds.")
    return result
    return wrapper

    Data Engineering Context and Trade-offs

    This decorator is highly useful in data engineering for profiling ETL steps, identifying bottlenecks in complex transformations (e.g., a Spark UDF, a Pandas operation, or a dbt model hook), and monitoring the performance of batch jobs. By applying this to specific functions within a data pipeline, engineers can pinpoint slow components, similar to how one might analyze Spark job stages or Snowflake query profiles.

    The primary trade-off is minimal overhead from the timing and logging operations. While negligible for most functions, for extremely high-frequency, low-latency calls, this overhead could become a consideration. For production, ensure logs are directed to a centralized logging system (e.g., Splunk, ELK stack) rather than just stdout.

    In the interview, also mention…

    Discuss the importance of functools.wraps for maintainability and debugging, and the choice of time.perf_counter for accuracy. Emphasize how this pattern aids in building observable and performant data pipelines.

    ⚡
    Pro Tip

    Red Flag: Forgetting @wraps (breaks introspection). Pro-Move: 'We use this + logging to metrics—every ETL step reports duration to DataDog.'

    Want all answers as a PDF for offline study?
    Seven focused volumes with 750+ in-depth answers — Answer Vault →

    Related Python/Coding Questions

    easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

    Level up your prep

    Recommended
    Educative
    Educative Unlimited

    800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

    Start learning →

    Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

    According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

    ← Back to all questionsMore Python/Coding questions →
    Categories
    All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
    By Company
    AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
    Interview Guides
    All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
    Products
    AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
    Company
    About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
    © 2026 DataEngPrep.tech. All rights reserved.
    AboutBlogContactDisclaimer