python1 Min Read

Implementation of Timeit function, Get performance numbers for a function

Gorav Singal

July 30, 2019

TL;DR

Create a Python decorator that wraps any function to measure its execution time using time.time(), enabling easy performance profiling across your codebase.

Implementation of Timeit function, Get performance numbers for a function

This is regarding the timeit implementation in python. The basic requirement comes when you want to see how much time your methods are taking. And, on the basis on those numbers you would want to take some action in optimising them.

You should use it on almost every method, and you can use any graphical tool to get the statistics per method. And, you can identify the area which needs improvement.

Implementation of timeit

Below is one implementation of timeit functionality, which implements it as a decorator.

"""
Decorator for taking performance numbers
"""
import time

def perf(method):
    """
    A decorator for fetching time taken by methods
    """
    def timed(*args, **kw):
        # get start time
        start_time = time.time()
        
        # calling the method
        result = method(*args, **kw)
        
        # get end time
        end_time = time.time()

        stats = {}
        stats['method'] = f'{method.__module__}::{method.__qualname__}'
        stats['timetaken'] = '%2.2f' % int((end_time-start_time)*1000)

        print(f'Performance numbers, method={stats["method"]}, timetaken={stats["timetaken"]}')
        return result

    return timed

How to use it

@perf
def test1():
    print('Im in method test1')
    time.sleep(2);

test1()

# Output
Performance numbers, method=__main__::test1, timetaken=2001.00

You can change logging with whatever suits you. I have used print(), but you can use logger to log this in your standard log stream.

Share

Related Posts

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Introduction This post has the complete code to send email through smtp server…

Python: How to generate string of arbitrary length of any alphabet characters

Python: How to generate string of arbitrary length of any alphabet characters

I was testing a bug where a field was limited to 255 characters only. I needed…

Python - How to Maintain Quality Build Process Using Pylint and Unittest Coverage With Minimum Threshold Values

Python - How to Maintain Quality Build Process Using Pylint and Unittest Coverage With Minimum Threshold Values

Introduction It is very important to introduce few process so that your code and…

Python - How to Implement Timed-Function which gets Timeout After Specified Max Timeout Value

Python - How to Implement Timed-Function which gets Timeout After Specified Max Timeout Value

Introduction We often require to execute in timed manner, i.e. to specify a max…

How to Solve Circular Import Error in Python

How to Solve Circular Import Error in Python

Introduction To give some context, I have two python files. (Both in same folder…

Python Code - How To Read CSV with Headers into an Array of Dictionary

Python Code - How To Read CSV with Headers into an Array of Dictionary

Introduction Lets assume we have a csv something similar to following: Python…

Latest Posts

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI video generation went from “cool demo” to “usable in production” in 2024-202…

AI Models in 2025 — Cost, Capabilities, and Which One to Use

AI Models in 2025 — Cost, Capabilities, and Which One to Use

Choosing the right AI model is one of the most impactful decisions you’ll make…

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

Generating one image with AI costs between $0.002 and $0.12. That might sound…

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

Two years ago, AI coding meant one thing: GitHub Copilot autocompleting your…

AI Agents Demystified — It's Just Automation With a Better Brain

AI Agents Demystified — It's Just Automation With a Better Brain

Let’s cut through the noise. If you read Twitter or LinkedIn, you’d think “AI…

Supply Chain Security — Protecting Your Software Pipeline

Supply Chain Security — Protecting Your Software Pipeline

In 2024, a single malicious contributor nearly compromised every Linux system on…