Skip to main content

Measure execution time and memory usage of Python functions

Project description

funcmetricsx

Lightweight Python toolkit for measuring execution time, CPU time, memory usage, and call statistics of functions and code blocks. thon toolkit forhelps developers understand performance characteristics of their code with CPU time, memory usage, and caland a simple decorator or context manager.


Features

  • Measure execution time
  • Measure CPU time
  • Measure peak memory usage
  • Call count summary
  • Supports sync and async functions
  • Decorator API
  • Context manager API
  • Optional arguments and result logging
  • Logger integration
  • Pure Python implementation
  • No external runtime dependencies
  • Works on Python 3.10+

Installation

pip install funcmetricsx

Quick Example

from funcmetricsx import metrics

@metrics()
def compute():
    return sum(i * i for i in range(10000))

compute()

Example output:

[funcmetricsx] | compute | time=0.0012s | cpu=0.0011s | peak_memory=10.25 KB
[funcmetricsx] | compute summary | calls=1 | avg_time=0.0012s | last_time=0.0012s | avg_cpu=0.0011s | last_cpu=0.0011s

Real World Examples

Example 1 — Measuring an API Request

import requests
from funcmetricsx import metrics

@metrics()
def fetch_users():
    r = requests.get("https://jsonplaceholder.typicode.com/users")
    return r.json()

fetch_users()

Output:

[funcmetricsx] | fetch_users | time=0.2341s | cpu=0.0120s | peak_memory=48.00 KB

Useful for understanding network latency vs CPU work.

Example 2 — Measuring Database Queries

import sqlite3
from funcmetricsx import metrics

conn = sqlite3.connect(":memory:")

@metrics(show_result=True)
def query_db():
    cur = conn.cursor()
    cur.execute("SELECT sqlite_version()")
    return cur.fetchone()

query_db()

Output:

[funcmetricsx] | query_db | time=0.0003s | cpu=0.0003s | result=('3.44.0',)

Helpful when profiling database access speed.

Example 3 — Detecting Slow Data Processing

import time
from funcmetricsx import metrics

@metrics()
def process_data():
    time.sleep(0.2)
    return "done"

process_data()

Output:

[funcmetricsx] | process_data | time=0.2001s | cpu=0.0001s

Shows that the time is mostly waiting, not CPU usage.

Example 4 — CPU Heavy Work

from funcmetricsx import metrics

@metrics()
def cpu_heavy():
    total = 0
    for i in range(10_000_000):
        total += i
    return total

cpu_heavy()

Output:

[funcmetricsx] | cpu_heavy | time=0.45s | cpu=0.44s

Here CPU time ≈ wall time, meaning the function is CPU-bound.

Example 5 — Track Multiple Calls

from funcmetricsx import metrics

@metrics()
def add(a, b):
    return a + b

add(1, 2)
add(3, 4)
add(5, 6)

Output:

[funcmetricsx] | add | time=0.0001s | cpu=0.0001s
[funcmetricsx] | add summary | calls=1 | avg_time=0.0001s

[funcmetricsx] | add | time=0.0001s | cpu=0.0001s
[funcmetricsx] | add summary | calls=2 | avg_time=0.0001s

[funcmetricsx] | add | time=0.0001s | cpu=0.0001s
[funcmetricsx] | add summary | calls=3 | avg_time=0.0001s

Great for profiling high-frequency functions.

Async Function Support

import asyncio
from funcmetricsx import metrics

@metrics()
async def fetch_data():
    await asyncio.sleep(0.1)
    return "done"

asyncio.run(fetch_data())

Output:

[funcmetricsx] | fetch_data | time=0.1003s | cpu=0.0002s

Works automatically with async def.

Measure Code Blocks

Sometimes you want to measure a specific block of code instead of a function.

import time
from funcmetricsx import measure_block

with measure_block("load-data"):
    time.sleep(0.2)

Output:

[funcmetricsx] | load-data | time=0.2002s | cpu=0.0001s

Show Function Arguments

from funcmetricsx import metrics

@metrics(show_args=True)
def multiply(a, b):
    return a * b

multiply(3, 4)

Output:

[funcmetricsx] | multiply | time=0.0001s | args=(3, 4)

Show Function Result

from funcmetricsx import metrics

@metrics(show_result=True)
def square(x):
    return x * x

square(5)

Output:

[funcmetricsx] | square | time=0.0001s | result=25

Logger Integration

Send metrics to a Python logger instead of printing.

import logging
from funcmetricsx import metrics

logging.basicConfig(
    filename="metrics.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)

logger = logging.getLogger("metrics")


@metrics(logger=logger)
def task():
    return sum(range(10000))


task()

you can check the output in metrics.log


Configuration Options

@metrics(
    show_time=True,
    show_cpu_time=True,
    show_memory=True,
    show_args=False,
    show_result=False,
    track_calls=True,
)

Option Description
show_time display execution time
show_cpu_time display CPU usage time
show_memory display peak memory usage
show_args show function arguments
show_result show returned value
track_calls maintain call statistics

Running Tests

pytest

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

funcmetricsx-0.1.0.tar.gz (10.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

funcmetricsx-0.1.0-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file funcmetricsx-0.1.0.tar.gz.

File metadata

  • Download URL: funcmetricsx-0.1.0.tar.gz
  • Upload date:
  • Size: 10.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for funcmetricsx-0.1.0.tar.gz
Algorithm Hash digest
SHA256 78a8cd71b6537ee75918de604b0da74a00b7b64191ac17217817615bfedcf975
MD5 fdfecaa5bf1018ce5108a9b3ff60952f
BLAKE2b-256 83bc9298e5c4282e010cfb38286793d9a8a58fff2aa0fe8e0a73e94b1427d941

See more details on using hashes here.

File details

Details for the file funcmetricsx-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: funcmetricsx-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 9.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for funcmetricsx-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9930f0ab10ff475858f44d09a473303574a6c5d0e4f00e0bb25e7cbf27bad82c
MD5 14558dddce6b63ddd82e9e252e1c3fe3
BLAKE2b-256 318376c458a9733efa170c13b6002f242a11320d231af0fe5278c5851ec22a4e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page